考虑这个程序:
#include <iostream>
#include <string>
#include <sstream>
#include <cassert>
int main()
{
std::istringstream stream( "-1" );
unsigned short n = 0;
stream >> n;
assert( stream.fail() && n == 0 );
std::cout << "can't convert -1 to unsigned short" << std::endl;
return 0;
}
我在 OS X 10.5.6 上的 gcc(版本 4.0.1 Apple Inc. build 5490)上试过这个,断言是真的;它无法将 -1 转换为无符号短。
然而,在 Visual Studio 2005(和 2008)中,断言失败并且 n 的结果值与编译器生成的隐式转换所期望的值相同 - 即“-1”是 65535,“-2”是 65534,等等. 但后来它在“-32769”处变得很奇怪,它转换为 32767。
这里谁对谁错?(-32769 到底是怎么回事??)