Can operator overloaders be member functions?

I'm overloading the << operator using the following prototype:

friend ostream& operator<<(ostream& sout, const Polynomial& p);

But I've found that using the following definition:

ostream& Polynomial::operator<<(ostream& sout, const Polynomial& p)

Compiles with the following error:

Polynomial.cpp:89: error: ‘std::ostream& Polynomial::operator<<(std::ostream&, const Polynomial&)’ must take exactly one argument

The error no longer occurs when I take out the Polynomial:: part, but I'm wondering why. Can operator overloaders not be member functions? Or is it because this function is a friend?
Last edited on
Operator member functions take a reference to object as first argument implicitely.

So operator Polynomial::operator<<(/*operands*/) is threated like operator<<(Polynomal&, /*operands) */

As operator<< takes two arguments, member version is left with only one left to define.
This is why you should define stream operator as non-member: as first argument should be stream it can only be a member of that stream, which you cannot change.
Topic archived. No new replies allowed.