为什么在这种情况下类型 bool 的输出等于 0?

REK*_*AUS 4 c++ boolean

#include <iostream>
#include <cmath>
using namespace std;

int
main ()
{
  cout << ('x' > 0xFF) || (3 * 5 < 35) && (53 > 5 * 3);
  cout << ('x' > 0xFF);
  cout << (3 * 5 < 35) && (53 > 5 * 3);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

我得到 001 即使据我所知它应该是 101 。

Kev*_*vin 6

根据C++ 运算符优先级<<具有比||and更高的优先级&&。所以

cout << ('x' > 0xFF) || (3 * 5 < 35) && (53 > 5 * 3);
Run Code Online (Sandbox Code Playgroud)

实际上被解析为(为了强调而添加了额外的空格)

( cout << ('x' > 0xFF) )    || (3 * 5 < 35) && (53 > 5 * 3);
Run Code Online (Sandbox Code Playgroud)

它打印出'x' > 0xFF(这是错误的)的结果并基本上忽略其余部分。为了得到你想要的东西,你需要把它用括号括起来:

cout <<    ( ('x' > 0xFF) || (3 * 5 < 35) && (53 > 5 * 3) );
Run Code Online (Sandbox Code Playgroud)

至于为什么(cout << A) || B首先有效,std::basic_ostream(它cout是一个实例)具有以下重载:

  1. operator<< - 将数据写入流并返回对流的引用(这使您可以将多个调用链接在一起)。
  2. operator bool - 返回流是否仍然有效。

所以(cout << A) || B是句法糖static_cast<bool>(cout.operator<<(A)) || B