布尔类型操作

boolean type manipulation

本文关键字:操作 类型 布尔      更新时间:2023-10-16

此代码

#include <iostream>
using namespace std;
int main(){
  bool t=false;
  cout<<t &&(!t)<<endl;
  return 0;
}

显示如下错误

类型为"bool"answers"binary"的无效操作数"operator<& lt;"

怎么了?这个我不明白,请给我解释一下。我认为&&!是在c++中定义的。

怎么了?

"类型'bool'和'到二进制'操作符<<'的无效操作数"

这意味着第二个<<操作符正在尝试对(!t)和'endl'执行。

<<具有比&&更高的优先级,因此您的cout语句执行如下:

(cout << t ) && ( (!t) << endl );

添加括号修复:

cout << (t && (!t) ) << endl ;

添加圆括号,使操作符的优先级正确:

cout << (t && !t) << endl;

等同于:

cout << false << endl;

&&的优先级低于<<,因此语句被计算为(cout << t) && (!t << endl);

c++操作符优先级

你需要更多的括号:

cout << (t && !t) << endl;

问题在于运算符优先级,因为 &&的优先级低于<<

cout<<(t && (!t))<<endl;  // ok!

同样,对于任何bool变量t,表达式t && (!t)总是得到false, t || (!t)总是得到true。:)