我正在学习 C++ 中的函数重载并遇到了这个问题:
void display(int a)
{
cout << "int" << endl;
}
void display(unsigned a)
{
cout << "unsigned" << endl;
}
int main()
{
int i = -2147483648;
cout << i << endl; //will display -2147483648
display(-2147483648);
}
据我了解,int
范围内给出的任何值(在我的情况下int
是 4 字节)都会调用display(int)
,并且此范围之外的任何值都将是模棱两可的(因为编译器无法决定调用哪个函数)。它对int
除最小值以外的所有值都有效,即-2147483648
编译失败并出现错误
重载的调用
display(long int)
不明确
但是对 a 取相同的值int
并打印该值给出2147483648
. 我真的对这种行为感到困惑。
为什么只有在传递最大负数时才会观察到这种行为?(如果 ashort
与-32768
- 事实上,在负数和正数具有相同二进制表示的任何情况下,行为是相同的)
使用的编译器:g++ (GCC) 4.8.5