c ++重载流运算符,引用参数和匿名实例

时间:2015-04-23 18:04:24

标签: c++ operator-overloading

如果我有一个带有重载流操作符的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;

1 个答案:

答案 0 :(得分:4)

由于运算符不应修改右操作数,因此应该通过const引用:

friend ostream& operator<< (ostream &out, const Value &val);

const引用可以绑定到临时对象,因此它可以工作(以及标准库如何做到这一点)。