假设我想打印数字参数(如果它们 > 1)或“无”(如果它们 <= 1)。我知道如何做到这一点的唯一方法是:
cout << "number of args: ";
if (argc > 1)
cout << argc - 1;
else
cout << "none";
cout << endl;
但我无法链接 <<
运算符(operator)。理想情况下,我希望能够执行以下操作:
cout << "number of args: "
<< argc > 1 ? argc - 1 : "none"
<< endl;
但这是不可能的,因为三元 if 的类型不同。
想法?
最佳答案
简单的方法。用字符串处理。
std::cout << "number of args: "
<< (argc > 1 ? std::to_string(argc - 1) : "none")
<< std::endl;
更改字符串会产生一些多余的成本。但是如果使用一次就容易阅读和维护。需要括号的原因是移位运算符 (<<) 的优先级高于三元条件运算符 (?:) 或关系运算符 (>)。
关于c++ - 使用 operator<<? 根据某些条件打印不同类型的不同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25477833/