[英]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.