Search This Blog

Monday, July 6, 2009

C++ Overloading the Output Operator <<

Here is the general prototype of an overloaded operator, <<
(a namespace operator(global overloaded), not a member operator,
so the left operand must be explicit)

ostream&
operator<< (ostream& os, const MyClass& myClass)
{
os << myClass.stuff;
os << endl;

return os;
}

since the left argument is an ostream reference,
the output operator must be defined as a nonmember function
(as opposed to the member function defined in a class)

if the operator tries to access the non-public member of MyClass, the operator must be declared as 'friend' inside MyClassReference:
C++ Primer, p1091, 741, 742, 743, 748(Friends)

No comments: