Reputation: 3955
When overloading the input or output operators (>> or <<) , I see that the function takes two arguments, a reference to an iostream object and a reference to whatever object we wish to input or output. An operator<< example for a Matrix object :
std::ostream& operator<< (std::ostream& stream, const Matrix& matrix);
When calling this function we only need to pass the Matrix object, for example :
Matrix m1;
cout<<m1;
What about the other ostream object argument? How does this work? Thanks in advance
Upvotes: 1
Views: 664
Reputation: 27365
What about the other ostream object argument? How does this work?
If the compiler finds:
a = b <op> c;
(where <op>
can be +, -, ==, >>, etc), the compiler will try the following resolutions:
a = operator <op>(b, c); // (1)
a = b.operator <op> (c); // (2)
This depends on the type of operator (for example, + is a binary operator and cannot be implemented in form (2)) and implementations available (the code you write and the resolution priority).
For operator << (your example above), these pieces of code are equivalent:
1:
Matrix m1;
cout<<m1;
2:
Matrix m1;
operator<<(cout, m1);
For native data types, std:::istream offers a member implementation:
int i;
cout.operator<<(i);
Upvotes: 1
Reputation: 306
Consider this case:
cout<<m1
Here cout is the first argument, m1 is second. The return value of this method call is not captured by your code.
Case 2:
cout << m1 << m2;
Here there will be two calls to operator. Return of the first call is passed as argument of next call.
Upvotes: 0
Reputation: 146940
The other argument is cout
itself. The call becomes operator<<(cout, m1)
.
If the operator only took one argument, you could write << m1;
as a complete statement, which you cannot.
Upvotes: 5