你能解釋一下為什么下面的代碼會得到這些結果嗎?
#include <iostream>
int main()
{
int x = -1;
unsigned int y = 1;
if (x > y)
std::cout << "true"。
else
std::cout << "false";
}
Output = true但是為什么?
uj5u.com熱心網友回復:
這里發生的是一個從int到unsigned int的隱式轉換,它恰好以下列方式發生。
int x = -a。
無符號 int y = x; //As far as y can hold only positive values,
//它現在持有UINT_MAX - (a 1)。
其中UINT_MAX是一個宏,它被定義為無符號int可以持有的最大值。
在你的例子中,x被轉換為UINT_MAX,這顯然是大于1的
uj5u.com熱心網友回復:
這里發生的是,這段代碼:
int x = -1。
unsigned int y = 1;
bool result = x > y;
被轉換為:
int x = -1;
unsigned int y = 1;
bool result = operator>(x, y)。
有兩個operator> 函式被定義:
bool operator>(int, int) 。
bool operator>(unsigned int, unsignedint) 。
但是你正在呼叫operator>(int, unsigned int)。所以編譯器將你的有符號int轉換為無符號int,然后呼叫operator>(unsigned int, unsigned int),這導致了一個bug。
避免這種情況的標準方法是打開編譯器警告。你可以使用-Wconversion警告,這將警告你這個特定的問題,或者更好的是通過-Wall來打開所有的警告。
為了修復代碼中的錯誤,你可以明確地告訴編譯器如何轉換比較運算子的引數
。#include <iostream>
int main()
{
int x = -1;
unsigned int y = 1;
if (x > static_cast<int>(y))
std::cout << "true"。
else
std::cout << "false";
}
但是要注意,如果你的無符號int大于可以裝入int的數量,還是會導致bug。最安全的解決方案是,如果你能使兩個變數都是相同的型別開始。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/321885.html
標籤:
上一篇:宣告常量時,模板成員函式決議失敗
