C ++重载流运算符,按引用引用的参数和匿名实例 [英] c++ overloading stream operator, parameters by reference and anonymous instances

查看:83
本文介绍了C ++重载流运算符,按引用引用的参数和匿名实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的POD带有重载的流运算符:

If I have a POD with an overloaded stream operator:

struct Value{
...
    friend ostream& operator<< (ostream &out, Value &val);
...
};

我不能在匿名实例中使用流运算符. 例如,我做不到:

I can't use the stream operator with anonymous instances. for example I can't do:

cout<<Value();

这给了我:

error: ambiguous overload for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘Value’)

另一方面,我可以按值传递POD,但我想避免复制.有办法吗?

On the other hand, I can pass the POD by value, but I would like to avoid the copy. Is there a way to both?

Value v1;
cout<<v1<<" "<<Value()<<endl;

推荐答案

由于操作员不应修改正确的操作数,因此应通过const参考引用它:

Since the operator should not modify the right operand, it should take it by const reference:

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

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

const references can bind to temporaries, so it will work (and that's how the standard library does it as well).

这篇关于C ++重载流运算符,按引用引用的参数和匿名实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆