如何使用 C++ 使用三元运算符编写以下条件
int condition1, condition2, condition3;
int / double result; //int or double
....
std::cout << ( condition1: result1 : "Error" )
<< ( condition2: result2 : "Error" )
<< ( condition3: result3 : "Error")...;
最佳答案
取决于什么类型是result1、result2
等
表达式 C ? expression1 : expression2
并非对所有类型的 expression1
和 expression2
都有效。粗略地说,它们必须可以转换为通用类型(可以在标准中阅读确切的规则和异常(exception)情况)。现在,如果 result
是字符串,那么您可以这样做:
std::cout << ( condition1 ? result1 : "Error" )
^^^
<< ( condition2 ? result2 : "Error")
^^^
<< etc.
但是如果结果是整数,例如,你不能这样做。
HTH
关于C++,三元运算符,std::cout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6611030/