Here is one example:
When you are overloading the << operator
for a class T
the signature will be:
std::ostream operator<<(std::ostream& os, T& objT )
where the implementation needs to be
{
//write objT to the os
return os;
}
For the <<
operator the first argument needs to be the ostream object and the second argument your class T object.
If you try to define operator<<
as a member function you will not be allowed to define it as std::ostream operator<<(std::ostream& os, T& objT)
.
This is because binary operator member functions can only take one argument and the invoking object is implicitly passed in as the first argument using this
.
If you use the std::ostream operator<<(std::ostream& os)
signature as a member function you will actually end up with a member function std::ostream operator<<(this, std::ostream& os)
which will not do what you want.
Therefore you need a operator that is not a member function and can access member data (if your class T has private data you want to stream, operator<<
needs to be a friend of class T).