问题描述
通过尝试,我了解到在cout语句中有必要在一个条件运算符周围加括号。这里有一个小例子:
By trying, I came to know that it is necessary to put brackets around a conditional operator in a cout statement. Here a small example:
#include <iostream>
int main() {
int a = 5;
float b = (a!=0) ? 42.0f : -42.0f;
// works fine
std::cout << b << std::endl;
// works also fine
std::cout << ( (a != 0) ? 42.0f : -42.0f ) << std::endl;
// does not work fine
std::cout << (a != 0) ? 42.0f : -42.0f;
return 0;
}
输出为:
42
42
1
为什么需要此支架?在这两种情况下,结果类型的条件运算符是已知的。
Why is this bracket necessary? The resulting type of the conditional operator is known in both cases, isn't it?
推荐答案
?:
运算符的优先级低于<<
运算符。也就是说,编译器将您最后一个语句解释为:
The ?:
operator has lower precedence than the <<
operator. I.e., the compiler interprets your last statement as:
(std::cout << (a != 0)) ? 42.0f : -42.0f;
这将首先传递(a!= 0)的布尔值
到cout。然后,该表达式的结果(即对cout的引用)将被转换为适当的类型以供在::操作符中使用(即 void *
:see ),并且取决于是否该值为真(即,cout是否没有设置错误标志),它将获取值42或值-42。最后,它会抛出那个值(因为没有什么用)。
Which will first stream the boolean value of (a!=0)
to cout. Then the result of that expression (i.e., a reference to cout) will be cast to an appropriate type for use in the ?: operator (namely void*
: see http://www.cplusplus.com/reference/iostream/ios/operator_voidpt/), and depending on whether that value is true (i.e., whether cout has no error flags set), it will grab either the value 42 or the value -42. Finally, it will throw that value away (since nothing uses it).
这篇关于cout语句中使用的条件运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!