0

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 ?

Nix
  • 351
  • 5
  • 13
  • Unfortunately, [the relevant answer in the dupe](http://stackoverflow.com/a/34954015/434551) is way down. – R Sahu Mar 01 '17 at 17:03

2 Answers2

4

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.

nwp
  • 9,623
  • 5
  • 38
  • 68
1

Your operator<< must be a non-member function. You cannot make it a "method" if you want to use it with std::cout on the left-hand side and your own class on the right-hand side.

But you can declare the operator<< as a friend if it needs access to private data of MyClass.

Christian Hackl
  • 27,051
  • 3
  • 32
  • 62