What is the correct way to overload stream operators << >> for my class?

I'm a little confused about how to overload stream operators for my C ++ class, since they seem to be functions of stream classes, not my class. What is 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 is working. It is not mentioned in the definition of the Thing class. I want him to be able to access members of my Thing class in its implementation - how to do this?

+5
source share
4 answers

. , , - friend Thing:

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

. , , (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;
}
+8

operator>> Thing.

+6

, , .

API, , .

, .

My favorite is to create a public Boost.Serialization style template function that can be used for streaming anyway, as well as for other things.

+2
source

All Articles