A stream insertion operator is a fancy name for the special function that prints to an iostream.
1 2 3 4 5 6 7 8 9 10 11 12
|
class Car
{
...
friend ostream& operator << ( ostream& outs, const Car& car );
};
ostream& operator << ( ostream& outs, const Car& car )
{
outs << car.year << " " << car.maker << " " << car.name << " (" << car.passenger << " passenger)";
return outs;
}
|
All output operators (stream insertion operators) will look something like this. The only differences is in how you want to format your output.
Notice that you could have easily used another function name:
1 2 3 4
|
void print_car( ostream& outs, const Car& car )
{
outs << car.year << ...;
}
|
There are only a couple of things that are important to take note of:
(1) The Car argument is a const reference.
(2) The insertion operator returns the stream passed as argument. (It needn't, but in most cases, as in your case, it should.)
(3) You use the argument stream instead of
cout.
(4) You don't print a newline at the end of the output. That makes it easy for you to say things later like:
1 2 3 4
|
Car my_audi_tt;
...
cout << "My " << my_audi_tt << " is awesome!\n";
|
My 2007 Audi TT (4 passenger) is awesome! |
Finally, there is an issue where how you print things matters. The example I gave you prints everything on one line. That's not the only way to do it. Choose how you (or your professor) prefer it.
[edit]
Oh yeah, I almost forgot:
(5) The insertion operator is always a friend function.
[/edit]
Hope this helps.