在内部类型的 C++ 二元运算符中,两个操作数应该具有相同的类型,如果不是,则其中一个操作数将根据层次结构转换为另一个操作数的类型:
long double
double
float
unsigned long long int
long long int
unsigned long int
long int
unsigned int
int
我的问题是:为什么unsigned T
比T
. 它只是一个任意的选择,还是转换T
成Unsigned T
而不是相反有一些优势。
更新:
//where `unsigned int` to `int` work better.
int a=-3;
unsigned int b=3;
cout << a+b; /* this will output the right result if b get converted to int,
which is not what really happen.*/
//where `int` to `unsigned int` work better.
int a=3;
unsigned int b=pow(2,20);
cout << a+b; /* this will output the right result if a get converted to unsigned int,
which is fortunately what really happen.*/
因此,我看不出与其他方式相比,convering T
toUnsigned T
具有更多优势。