Nix Nix -4 years ago 110
C++ Question

Can't use operator<< as a method?

I used to define operator<< as a function, like I did with most of my operators.

class MyClass {
int myAttribute;

public :

MyClass(int 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 ?

Answer Source

Your std::ostream& MyClass::operator<< (std::ostream &stream) is used when you write MyClass m; m << std::cout;. That is not what you intended.

If you add std::ostream &std::ostream::operator<<(const MyClass &m) then that would work for MyClass m; std::cout << m;, but it requires you to change the standard headers, which you cannot, so the non-member version is the only viable option.

Note that the non-member version is not part of MyClass and therefore cannot access private members of MyClass. If you need that you can add friend std::ostream& operator<< (std::ostream &stream, const MyClass &mc); to MyClass to make that possible.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download