C++ 为三值运算将int赋值给bool

C++ 为三值运算将int赋值给bool,c++,ternary-operator,C++,Ternary Operator,bool three=3;隐式地将3转换为bool,因此three的值将为true(任何非零数字将转换为true,零转换为false) 还注意到,三元条件比赋值(C++和java)具有更高的优先级。 所以intx=three?3:0;相当于intx=(three?3:0); intx=(三?3:0);因此相当于intx=(真?3:0)这相当于int x=3;没有bool接受int。我认为这在Java中没有什么不同。bool three=3@juanchopanza@free_mind任何等于零的

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

还注意到,三元条件比赋值(C++和java)具有更高的优先级。 所以

intx=three?3:0;
相当于
intx=(three?3:0);


intx=(三?3:0);
因此相当于
intx=(真?3:0)
这相当于
int x=3;

没有
bool
接受
int
。我认为这在Java中没有什么不同。
bool three=3
@juanchopanza@free_mind任何等于零的值都是
false
;否则-
true
int x=three?3:0
被解读为
(int x=3)?3:0
,但被解读为
int x=(three?3:0)
,即三元表达式
three?3:0
被计算(如果
three
为真则返回3,如果为假则返回0),然后,
x
被分配这个表达式的结果。在这种情况下,
three
被分配
true
,因为它被分配了一个非零的
int
,它被隐式转换。事实上,我也不理解-4。考虑到你来自Java,我可以看到混淆。但是Java奇怪的自动装箱,我认为Java conditional非常奇怪。谢谢!我不知道隐式转换。@free_mind-没有隐式转换,但有隐式转换。转换是在源代码中编写的东西,用于告诉编译器进行转换,因此转换总是显式的。转换可以是显式的(即使用转换完成)或隐式的(由编译器完成,因为语言规则告诉它)。