简体   繁体   English

对C ++中的类型转换感到困惑

[英]Confused about type conversion in C++

In C++, the following lines have me confused: 在C ++中,以下几行让我感到困惑:

int temp = (int)(0×00);

int temp = (0×00int);

What is the difference between those 2 lines? 那两条线有什么区别?

Both are invalid because you are using × instead of x : 两者都是无效的,因为您使用的是×而不是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"

But even fixing that, the second still isn't valid C++ because you can't write 0x00int : 但是即使解决了这一点,第二个仍然不是有效的C ++,因为您不能编写0x00int

test.cpp:6:13: invalid suffix "int" on integer constant

The first is valid (after changing × to x ) and assigns the value 0 to temp. 第一个有效(将×更改为x ),并将值0分配给temp。 The cast is unnecessary here though - you don't need a cast just because the constant is written in hexadecimal. 不过,此处的强制转换是不必要的-您不必仅因为常量以十六进制形式编写就进行强制转换。 You can just write: 您可以这样写:

int temp = 0x00;

Ways to cast: 投放方式:

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

The fun thing about static_cast and reinterpret_cast is that a good compiler will warn you when you're using them wrong, at least in some scenarios. static_cast和reinterpret_cast的有趣之处在于,至少在某些情况下,当您错误地使用它们时,好的编译器会警告您。

Visual Studio 2005 for example will throw an error if you try to reinterpret_cast 0x00 to an int, because that conversion is available in a safe way. 例如,如果您尝试将reinterpret_cast 0x00转换为int,则Visual Studio 2005将引发错误,因为该转换可以安全的方式进行。 The actual message is: "Conversion is a valid standard conversion, which can be performed implicitly or by use of static_cast, C-style cast or function-style cast". 实际的消息是:“转换是有效的标准转换,可以隐式执行,也可以使用static_cast,C样式转换或函数样式转换进行转换”。

The first will assign 0 to temp 第一个将0分配给temp

Second will result in compilation error. 第二将导致编译错误。

When the scanner sees it expects it to be followed with hexadecimal digit(s), but when it sees i which is not a valid hex digit it gives error. 当扫描仪看到它期望它后面跟随一个十六进制数字,但是当它看到i而不是一个有效的十六进制数字时,它将给出错误。

The first one takes the hex value 0x00 as an int, and uses it to initialize the variable temp. 第一个将十六进制值0x00作为一个整数,并使用它来初始化变量temp。

The second one is a compile error. 第二个是编译错误。

First line is a valid C++, which basically equate to 第一行是有效的C ++,基本上等于

int temp = 0; 

while the second one will fail to compile (as suggested by everyone here). 而第二个将无法编译(如此处每个人的建议)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM