Output streams use the insertion (<<) operator for the standard types. Now you will learn how to overload the << operator for your own classes.
Example 8, on page 376, illustrated the use of a Date structure. A date is an ideal candidate for a C++ class in which the data members (month, day and year) are hidden from view. A Date object should know how to display itself, and an output stream is the logical destination.
The following code displays a date on cout in a manner consistent with the preceding examples.
Date dt( 1, 2, 90 );
cout << dt;
To get the cout object to accept a Date object after the insertion operator, you must overload the insertion operator to recognize an ostream object on the left and a Date on the right. The overloaded << operator function must then be declared as a friend of class Date so that it can access the private data within a Date object.
Example 14
Example 14 overloads the << operator to accept an ostream object on the left and a Date object on the right:
// exios114.cpp
// Overloading the << operator
#include <iostream.h>
class Date
{
int mo, da, yr;
public:
Date( int m, int d, int y )
{
mo = m; da = d; yr = y;
}
friend ostream& operator<< ( ostream& os, Date& dt );
};
ostream& operator<< ( ostream& os, Date& dt )
{
os << dt.mo << '/' << dt.da << '/' << dt.yr;
return os;
}
void main()
{
Date dt( 5, 6, 77 );
cout << dt;
}
When you run this program, it prints the date:
5/6/77
Note that the overloaded operator returns a reference to the original ostream object, which means you can combine various insertions:
cout << "The date is" << dt << flush;