The idea is that you can "overload" an operator for your own data types.
The shift operators, written
<< and
>>, are defined over integer data types (like
int and
char).
However,
cout is an
std::ostream, which is
not an integer, and it would make no sense to apply an arithmetic shift to a stream.
Even so, you can still create a definition for the operators. (Remember, operator overloads are actually just functions that get called when you use an operator on your data type. For example, you could write:
1 2 3 4 5 6
|
struct point
{
int x, y;
point(): x( 0 ), y( 0 ) { }
point( int x, int y ): x( x ), y( y ) { }
};
|
If you wanted to add two points, you can write a function to do it:
1 2 3 4
|
point add( const point& a, const point& b )
{
return point( a.x + b.x, a.y + b.y );
}
|
1 2 3
|
point p1, p2, p3;
...
p3 = add( p1, p2 );
|
However, it is prettier to make the '+' operator do it:
1 2 3 4
|
point operator + ( const point& a, const point& b )
{
return point( a.x + b.x, a.y + b.y );
}
|
1 2 3
|
point p1, p2, p3;
...
p3 = p1 + p2;
|
The whole trick here is that
the overloaded operator does not have to actually do what you think it will.
That's right. You could have written:
1 2 3 4
|
point operator + ( const point& a, const point& b )
{
return point( -7, a.x * b.x - b.y );
}
|
But now, of course:
|
p3 = p1 + p2; // Hey! This doesn't do what I think it should do!
|
The standard library used the
visual suggestion (common in shell scripting) that items will be "redirected" (or "piped") into the stream.
Hence,
cout << "Hello world!\n";
suggests that the text string will be "directed" (or printed) into the output terminal (or file).
In this case it does make sense due to historical reasons. In general, however, you should use the principle of least surprise and make overloaded operators do what they say they will. Add should add, etc.
I hope this makes sense.