Use operator overloading to provide a
friend left-shift operator, operator<<.
#include <iostream>
class Fred {
public:
friend std::ostream& operator<< (std::ostream& o, Fred const& fred);
...
private:
int i_; // Just for illustration
};
std::ostream& operator<< (std::ostream& o, Fred const& fred)
{
return o << fred.i_;
}
int main()
{
Fred f;
std::cout << "My Fred object: " << f << "\n";
...
}
We use a non-member function (a
friend in this case)
since the
Fred object is the right-hand operand of the
<< operator.
If the
Fred object was supposed to be on the left hand side of the
<<
(that is,
myFred << std::cout rather than
std::cout << myFred), we could
have used a member function named
operator<<.
Note that operator<< returns the stream. This is so the output operations
can be cascaded.