问题描述
调试后,我发现三元运算符?:
没有优先级.我的问题是为什么?
我有以下代码:
After debugging I found that ternary operator ?:
does not have priority. My question is why?
I have the following code:
bool T = true;
cout << ((T == true) ? "true" : "false") << endl;
cout << (T == true) ? "true" : "false";
输出:
true
1
实时演示: http://ideone.com/Tkvt9q
推荐答案
条件运算符确实具有优先级(尽管由于其三进制性质而有些复杂);但是优先级很低.由于它低于<<
,因此第二个解析为
The conditional operator does have a precedence (albeit slightly complicated by its ternary nature); but that precedence is very low. Since it's lower than <<
, the second is parsed as
(cout << (T == true)) ? "true" : "false";
流式传输 T == true
的布尔值,然后求值(但忽略)表达式"true"
.如果启用了明智的警告,大多数编译器都会给出警告.
streaming the boolean value of T == true
, then evaluating (but ignoring) the expression "true"
. Most compilers will give a warning, if you enable a sensible set of warnings.
这里是对运算符优先级的引用,显示的<<
优先级(7)比?:
(15):http://en.cppreference.com/w/cpp/language/operator_precedence
Here is a reference to the operator precedences, showing <<
with a higher precedence (7) than ?:
(15): http://en.cppreference.com/w/cpp/language/operator_precedence
这篇关于为什么运算符`?:`没有优先级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!