Search code examples
c++operator-overloadingstream-operators

What's the right way to overload the stream operators << >> for my class?


I'm a bit confused about how to overload the stream operators for my class in C++, since it seems they are functions on the stream classes, not on my class. What's the normal way to do this? At the moment, for the "get from" operator, I have a definition

istream& operator>>(istream& is, Thing& thing) { // etc...

which works. It's not mentioned in the definition of the Thing class. I want it to be able to access members of my Thing class in its implementation - how do I do this?


Solution

  • Your implementation is fine. The only additional step you need to perform is to declare your operator as a friend in Thing:

    class Thing {
    public:
      friend istream& operator>>(istream&, Thing&);
      ...
    }