在 C++ 流中使用三元运算符可以吗?

Is it ok to use ternary operator in C++ streams?

以下代码:

#include <iostream>
using namespace std;
struct A{int number=10;};

int main()
{
   A* a = new A();
   cout<<"A val: "<< a==nullptr?"":a->number<<endl;
}

使用 c++11 在 gcc 4.7 上编译得到:

error: invalid operands of types 'int' and '' to binary 'operator <<'

我不明白为什么,正确的方法是什么?我希望空检查尽可能短,因为我希望它们很常见。

您发现运算符 << 的绑定与您预期的不同。

使用:

cout << "A val: " << (a==nullptr ? "" : a->number) << endl;

(或者您刚刚打错了,错过了 ?: 中的 :

首先:是的,您可以对 std::ostream 使用三元运算符,但注意运算符优先级。如果你打算这样做,你需要做这样的事情:

cout << "My name is: " << (my != nullptr ? my->name() : "don't know") << '\n';

换句话说,将三元表达式封装在括号中。

其次,第二个和第三个操作数必须可转换为同一类型。换句话说,您的示例将不起作用,因为如果 a 为空,您试图插入字符串文字 (""),或者实际数字 (a->number,其类型int) 如果 a 不为空。

第三,你需要修正语法。但是@quamrana 已经解决了那个问题。