您应该使用reinterpret_cast<char *>而不是static_cast<char *>,因为数据类型不相关:例如,您可以在指向子类的指针与超类之间转换,或者在int之间转换和long,或void *与任何指针之间,但unsigned int *到char *不是“安全”,因此您无法使用static_cast。< / p> 不同之处在于,在C ++中,您有各种类型的强制转换:...
static_cast can be used to convert from an int to a char. However, the resulting char may not have enough bits to hold the entire int value. Again, it is left to the programmer to ensure that the results of a static_cast conversion are safe. ...
使用C++样式转换从static_cast *转换为类型*:static_cast或reinterpret_cast 、、、 因此,如果您从Void*转换为Type*或从Type*转换为Void*,您应该使用:{}void func(void *p) Params *params = reinterpret_cast<Params*>(p);对我来说,static_cast此外,转换的方向也很重要。也就是说,我是否 浏览1提问于2010-...
運算子 static_cast 也可以用來執行任何隱含轉換,包括標準轉換和使用者定義的轉換。 例如:C++ 複製 // static_cast_Operator_3.cpp // compile with: /LD /GR typedef unsigned char BYTE; void f() { char ch; int i = 65; float f = 2.5; double dbl; ch = static_cast<char>(i); // int ...
static_cast 相当于C语言中的强制转换:(类型)表达式或类型(表达式),用于各种隐式转换 非const转const、void*转指针、int和char相互转换 用于基类和子类之间的指针和引用转换,非指针直接报错 向上转化是安全的,如果向下转能(指针或引用)成功但是不安全,结果未知; ...
ch = static_cast<char>(i); // int to char dbl = static_cast<double>(f); // float to double ... i = static_cast<BYTE>(ch); ... } Thestatic_castoperator can explicitly convert an integral value to an enumeration type. If the value of the integral type does not fall within th...
| (static_cast<uint32_t>(ptr[2]) << 16) | (static_cast<uint32_t>(ptr[3]) << 24)); } Should be: return ((static_cast<uint32_t>(static_cast<unsigned char>(ptr[0]))) | (static_cast<uint32_t>(static_cast<unsigned char>(ptr[1])) << 8) ...
struct Foo{}; struct Bar{}; int main(int argc, char** argv) { Foo* f = new Foo; Bar* b1 = f; // (1) Bar* b2 = static_cast<Bar*>(f); // (2) Bar* b3 = dynamic_cast<Bar*>(f); // (3) Bar* b4 = reinterpret_cast<Bar*>(f); // (4) Bar* b5 = const_cast<...
Static_cast has two uses. First it will force a conversion that could have happened implicitly. For example: double value = 1.45; double remainder = value - static_cast<int >(value); Here we force a conversion that could be done implicitly with an extra temporary variable. The other use,...
Hint: For input, you can convert an int into an enum with static_cast. 1 2 3 4 DayOfWeek day;intdayNumber; cin >> dayNumber; day =static_cast<DayOfWeek>(dayNumber); and the output I am supposed to get should look like this: ...