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

后端 未结 4 1666
礼貌的吻别
礼貌的吻别 2020-12-19 09:49

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 no

4条回答
  •  眼角桃花
    2020-12-19 10:31

    The other answers are right. In case it helps you, here's a code example (source):

    class MyClass {
      int x, y;
    public:
      MyClass(int i, int j) { 
         x = i; 
         y = j; 
      }
      friend ostream &operator<<(ostream &stream, MyClass ob);
      friend istream &operator>>(istream &stream, MyClass &ob);
    };
    
    ostream &operator<<(ostream &stream, MyClass ob)
    {
      stream << ob.x << ' ' << ob.y << '\n';
    
      return stream;
    }
    
    istream &operator>>(istream &stream, MyClass &ob)
    {
      stream >> ob.x >> ob.y;
    
      return stream;
    }
    

提交回复
热议问题