Overloading is nothing more than writing another function. Do you know what an overloaded function is? If not:
1 2
|
void foo( int x ) { cout << "foo( int x = " << x << " )" << endl; }
void foo( char c ) { cout << "foo( char c = " << c << " )" << endl; }
|
The function foo() is said to be overloaded, because there are actually multiple functions named "foo". They differ, in this case, only by the type of parameter they take.
Now for operators. Operators are functions that are called with special syntax. Normally, you use parentheses to call functions. For example, to use the above functions, foo( 4 ) says to call function foo with parameter 4.
You don't (typically) call operator functions with (). For example, if I write the following function:
1 2 3 4
|
bool operator==( unsigned u, string const& s )
{
// Do something useful here...
}
|
Then I can call the above function like this:
1 2 3 4 5 6
|
string myStr = "Hello world!";
unsigned myUns = 12;
if( myUns == myStr ) // This calls the above operator== function
{
}
|
So you need to "overload" the "<<" operator for Book. There's a couple ways to do it. I'm not sure which way you were taught. The most general way is:
1 2 3 4 5 6 7 8
|
class Book {
// ...
template< typename charT, typename Traits > friend
std::basic_ostream<charT, Traits>& operator<<(
std::basic_ostream<charT, Traits>& os, Book const& book ) {
// return os << book.title << ... etc
}
};
|
Another less general way is:
1 2 3 4 5 6
|
class Book {
// ...
friend std::ostream& operator<<( std::ostream& os, Book const& book ) {
// return os << book.title << ... etc
}
};
|
I'm not sure if you were taught to write the function as a friend of the class or as a free function. I typically write them as friends because typically the output operator will want to output protected and/or private data that you'd otherwise have to write accessors for if you wrote operator<< as a non-friend free function.