Overloading the <<
Operator
To redefine the <<
operator so that you use it with cout
to display an object’s contents, you define a friend operator function that has the following form:
ostream & operator<<(ostream & os, const c_name & obj){ os << ... ; // display object contents return os;}
Here c_name
represents the name of the class. If the class provides public methods that return the required contents, you can use those methods in the operator function and dispense with the friend status.
Get C++ Primer Plus now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.