Overloading C++ Insertion Operator (<<) for a class
Solution 1
You probably put your operator<<
inside a class declaration. That means it takes an extra hidden parameter (the this
parameter). You need to put it outside of any class declaration.
Solution 2
The insertion operator (<<) can be used as a member function or a friend function.
operator << used as a member function
ostream& operator<<(ostream& os);
This function should be invoked as :
dom << cout;
In general if you are using the operator as a member function, the left hand side of the operator should be an object. Then this object is implicitly passed as an argument to the member function. But the invocation confuses the user and it does not look nice.
operator << used as a friend function
friend ostream& operator<<(ostream& os, const Domino& obj);
This function should be invoked as :
cout << dom;
In this case the object dom
is explicitly passed as a reference. This invocation is more traditional and user can easily understand the meaning of the code.
AFraser
Software developer from Brisbane, Australia currently in NYC.
Updated on June 04, 2022Comments
-
AFraser 7 months
I'm trying to write a class that overloads the insertion operator but in my header file I get the error.
Overloaded 'operator<<' must be a binary operator (has 3 parameters)
Here is my code:
.h file
ostream & operator<<(ostream & os, Domino dom);
.cpp file
ostream & operator<< (ostream & os, Domino dom) { return os << dom.toString(); }
I'm following a text book and this is what they use as an example but its not working for me.. Any suggestions?
-
suraj rathod over 6 yearsinsertion an extraction overloading without using friend function