为何cout中直接写sizeof(unsigned int)==sizeof(int)会编译报错?
问题原因解析
核心问题:运算符优先级差异
先看能正常运行的代码:
bool a = sizeof(unsigned int) == sizeof(int); cout << "(taille unsigned integer = integer) ? " << a;
这段代码里,sizeof(unsigned int) == sizeof(int)会优先计算,得到一个bool类型的结果赋值给a,之后cout只是按顺序输出字符串和bool值,完全符合语法规则。
再看报错的代码:
cout << "(taille unsigned integer = integer) ? " << sizeof(unsigned int) == sizeof(int);
这里的问题出在C++运算符优先级:<<的优先级比==更高。编译器会把这段代码解析成:
(cout << "(taille unsigned integer = integer) ? " << sizeof(unsigned int)) == sizeof(int);
也就是说,编译器先执行cout的两次输出操作,得到的结果是std::ostream对象(<<运算符会返回ostream的引用,也就是cout本身),然后试图把这个ostream对象和sizeof(int)的结果(size_t类型,通常等价于unsigned long)做==比较——这两种类型根本不能直接比较,因此抛出编译错误。
错误信息中文翻译
对二元表达式的操作数无效('std::basic_ostream
::__ostream_type'(别名 'basic_ostream<char, std::char_traits >')和 'unsigned long')
快速解决办法
如果想把判断结果直接嵌入输出语句,只需要给sizeof(unsigned int) == sizeof(int)加上括号,强制让它优先计算:
cout << "(taille unsigned integer = integer) ? " << (sizeof(unsigned int) == sizeof(int));
内容的提问来源于stack exchange,提问作者Marc Le Bihan
相关产品推荐
相关产品推荐

