问题
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