下面的代碼:可以在C++流中使用三元運算符嗎?
#include <iostream>
using namespace std;
struct A{int number=10;};
int main()
{
A* a = new A();
cout<<"A val: "<< a==nullptr?"":a->number<<endl;
}
編譯海合會4.7和C++ 11給出:
error: invalid operands of types 'int' and '' to binary 'operator <<'
我不明白爲什麼,會是正確的方式做到這一點呢?我希望儘可能縮短空值檢查,因爲我期望它們非常普遍。
對於大多數人來說,三元運算符具有[令人驚訝的低優先級](http://en.cppreference.com/w/cpp/language/operator_precedence)。我的建議:避免它,只要你不確定它的作用:你的同事會感謝你。 – Wolf