C++重载流操作符,通过引用传递参数和匿名实例

3
如果我有一个带有重载流运算符的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个回答

4

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

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

const引用可以绑定到临时对象,因此它将起作用(这也是标准库的工作方式)。


谢谢,那个方法可行!不幸的是,由于我是新用户,我还不能给你点赞。 - Haytham Yaghi
@HaythamYaghi 没问题。一旦计时器允许,您仍然可以接受 :-) - Angew is no longer proud of SO

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接