I used to define operator<< as a function, like I did with most of my operators.
class MyClass {
int myAttribute;
public :
MyClass(int attr):
myAttribute(attr){}
int getter() {return myAttribute;}
};
MyClass operator+(MyClass mc1, MyClass mc2)
{
MyClass mc(mc1.getter()+mc2.getter());
return mc;
}
std::ostream& operator<< (std::ostream &stream, MyClass mc)
{
stream << mc.getter();
return stream;
}
All this works well but I was told that I could define it as a method. I removed the definitions of operator+ and operator<< and I got no problem with operator+
MyClass MyClass::operator+(MyClass mc1)
{
MyClass mc(mc1.getter()+myAttribute);
return mc;
}
but it's doesn't work with operator<<
std::ostream& MyClass::operator<< (std::ostream &stream)
{
stream << myAttribute;
return stream;
}
I get the error :
error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'MyClass')
What do I miss ?