使用cout输出按位运算符的结果时编译错误

Bis*_*ist 1 c++ compiler-errors operator-precedence

我可以做这个 int c= 0xF^0xF; cout << c;

但是cout << 0xF^0xF;不会编译.为什么?

son*_*yao 5

根据C++ Operator Precedence,operator<<具有更高的优先级operator^,因此cout << 0xF^0xF;等效于:

(cout << 0xF) ^ 0xF;
Run Code Online (Sandbox Code Playgroud)

cout << 0xF返回cout(即a std::ostream),不能用作操作数operator^.

您可以添加括号以指定正确的优先级:

cout << (0xF ^ 0xF);
Run Code Online (Sandbox Code Playgroud)

  • @Bist Bitwise运算符`^ | &`的优先级低于值算术运算符`+ - */<< >>`.最初`<<`是左移运算符,与乘法类似.所以你可能写'1 << 3 | 1 << 2`或`1 << 3 ^ 1 << 2`.然后,当`<<`被选为流提取运算符时,优先级没有改变,因为这将更加令人困惑. (4认同)