如果我有一个带有重载流操作符的POD:
struct Value{
...
friend ostream& operator<< (ostream &out, Value &val);
...
};
我不能将流操作符与匿名实例一起使用。 例如,我无法做到:
cout<<Value();
这给了我:
error: ambiguous overload for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘Value’)
另一方面,我可以通过值传递POD,但我想避免复制。两者都有办法吗?
Value v1;
cout<<v1<<" "<<Value()<<endl;
答案 0 :(得分:4)
由于运算符不应修改右操作数,因此应该通过const
引用:
friend ostream& operator<< (ostream &out, const Value &val);
const
引用可以绑定到临时对象,因此它可以工作(以及标准库如何做到这一点)。