c++ overloading stream operator, parameters by reference and anonymous instances

萝らか妹 提交于 2020-01-11 09:56:09

问题


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();

This gives me:

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

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;

回答1:


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 references can bind to temporaries, so it will work (and that's how the standard library does it as well).



来源:https://stackoverflow.com/questions/29831113/c-overloading-stream-operator-parameters-by-reference-and-anonymous-instances

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!