Reputation: 493
So I'd like some clarification over overloading the print operator <<
now this is how I have learned to do it:
1) ostream& operator<<(ostream& os, const Vector& v1)
in this example we've got some Vector class that holds 3 integers.
I saw somebody try this instead:
2) ostream& operator<<(ostream& os, Vector& v1)
so the difference is v1 is just a reference and not a const reference. The compiler then couldn't print any Vector objects that weren't Lvalues for example he also overloaded the * operator to be able to do things such as v1 * 2, simple vector times a scalar. for example :
std::cout << v1 << std::end - this works (v1 is a vector) std::cout << v1 * 2 << std::end - this does not work
However when we changed the signature to be by value:
3) ostream& operator<<(ostream& os, Vector v1)
his print was able to work... and I'm left wondering why this all happened?
Why couldn't the compiler recognize overload (2) for v1 * 2 but why sending it by value to (3) did work
Upvotes: 0
Views: 82
Reputation: 11250
v1 * 2
would return a temporary, the second overload can't be used because non-const lvalue references don't bind to temporaries.
The third overload is used copying the value returned by v1 * 2
Upvotes: 0