In order to use cout as such : std::cout << myObject, why do I have to pass an ostream object? I thought that was an implicit parameter.
ostream &operator<<(ostream &out, const myClass &o) {
out << o.fname << " " << o.lname;
return out;
}
Thanks
In C++, stream insertion operator “<<” is used for output and extraction operator “>>” is used for input. We must know the following things before we start overloading these operators. 2) These operators must be overloaded as a global function.
Fortunately, by overloading the << operator, you can! Overloading operator<< is similar to overloading operator+ (they are both binary operators), except that the parameter types are different.
You can redefine or overload the function of most built-in operators in C++. These operators can be overloaded globally or on a class-by-class basis. Overloaded operators are implemented as functions and can be member functions or global functions. An overloaded operator is called an operator function.
Notes: The relational operators ( == , != , > , < , >= , <= ), + , << , >> are overloaded as non-member functions, where the left operand could be a non- string object (such as C-string, cin , cout ); while = , [] , += are overloaded as member functions where the left operand must be a string object.
You aren't adding another member function to ostream
, since that would require redefining the class. You can't add it to myClass
, since the ostream
goes first. The only thing you can do is add an overload to an independent function, which is what you're doing in the example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With