![]() |
![]() |
![]() |
![]() |
![]() |
|
You know that the output operator, <<, takes two operands: The
operand on the left tells the output operator where to put data, and the
operand on the right is an object of some sortpossibly a class object.
To overload the output operator, you need to know that the left-side
operand, such as cout, is a class object belonging to the
ostream class. Moreover, the object returned by the output operator
is supposed to be the same object that is supplied as the left-side
operand.
Accordingly, to overload the output operator, you use a specialized version of the general pattern for operator overloading:
ostream& operator<<
(ostream& output_stream, right parameter type and name) {
statements
return output_stream;
}
Note the ampersands in the pattern for overloading the output operator.
These particular ampersands tell the C++ compiler that you do not want
your program to make copies of the ostream object either at the time
of call or at the time of return.