[英]Confused about type conversion in C++
在C ++中,以下几行让我感到困惑:
int temp = (int)(0×00);
int temp = (0×00int);
那两条线有什么区别?
两者都是无效的,因为您使用的是×
而不是x
:
test.cpp:6: error: stray '\215' in program
test.cpp:6: error: expected primary-expression before "int"
test.cpp:6: error: expected `)' before "int"
但是即使解决了这一点,第二个仍然不是有效的C ++,因为您不能编写0x00int
:
test.cpp:6:13: invalid suffix "int" on integer constant
第一个有效(将×
更改为x
),并将值0分配给temp。 不过,此处的强制转换是不必要的-您不必仅因为常量以十六进制形式编写就进行强制转换。 您可以这样写:
int temp = 0x00;
投放方式:
int temp = (int)0x00; // Standard C-style cast
int temp = int(0x00); // Function-style cast
int temp = static_cast<int>(0x00); // C++ style cast, which is clearer and safer
int temp = reinterpret_cast<int>("Zero"); // Big-red-flag style unsafe cast
static_cast和reinterpret_cast的有趣之处在于,至少在某些情况下,当您错误地使用它们时,好的编译器会警告您。
例如,如果您尝试将reinterpret_cast 0x00转换为int,则Visual Studio 2005将引发错误,因为该转换可以安全的方式进行。 实际的消息是:“转换是有效的标准转换,可以隐式执行,也可以使用static_cast,C样式转换或函数样式转换进行转换”。
第一个将0
分配给temp
第二将导致编译错误。
当扫描仪看到0×
它期望它后面跟随一个十六进制数字,但是当它看到i
而不是一个有效的十六进制数字时,它将给出错误。
第一个将十六进制值0x00作为一个整数,并使用它来初始化变量temp。
第二个是编译错误。
第一行是有效的C ++,基本上等于
int temp = 0;
而第二个将无法编译(如此处每个人的建议)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.