A Common Kind of Friend: Overloading the <<
Operator
One very useful feature of classes is that you can overload the <<
operator so that you can use it with cout
to display an object’s contents. In some ways, this overloading is a bit trickier than the earlier examples, so we’ll develop it in two steps instead of in one.
Suppose trip
is a Time
object. To display Time
values, we’ve been using Show()
. Wouldn’t it be nice, however, if you could do the following?
cout << trip; // make cout recognize Time class?
You can do this because <<
is one of the C++ operators that can be overloaded. In fact, it already is heavily overloaded. In its most basic incarnation, the <<
operator is one of C and C++’s bit manipulation operators; it shifts bits left ...
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.