将 int 分配给 bool 以进行三元运算

Assigning an int to a bool for ternary operation

我是 c++ 的新手,正在尝试了解条件(三元)运算符的工作原理。我熟悉它在 java 中的用法,但对我在 c++

中看到的一个例子感到非常困惑
int main() 
{
   bool three = 3;
   int x = three ? 3 : 0;
   cout << x << "\n";
   return 0;
}

首先,bool 数据类型如何接受 int?第二,int x = three,这不是赋值,不是对x == 3的条件测试吗?或者是说 "create an int called x and assign it 3 if three == 3 else 0?"

bool three = 3; 隐式地 3 转换为 bool,因此 three 的值将是 true。 (任何非零数字将转换为 true,零将转换为 false。)

另请注意,三元条件的 优先级 高于赋值(在 C++ 和 Java 中)。

所以 int x = three ? 3 : 0; 等价于 int x = (three ? 3 : 0);.

int x = (three ? 3 : 0); 因此等同于 int x = (true ? 3 : 0); 等同于 int x = 3;