C++/Overload/Stream Operator

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Overload stream operator

#include <iostream>
#include <fstream>
using namespace std;
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;
}
int main()
{
  MyClass object1(1, 2), object2(3, 4);
  ofstream out("test");
  if(!out) {
    cout << "Cannot open output file.\n";
    return 1;
  }
  out << object1 << object2;
  out.close();
  ifstream in("test");
  if(!in) {
    cout << "Cannot open input file.\n";
    return 1;
  }
  MyClass object3(0, 0), object4(0, 0);
  in >> object3 >> object4;
  cout << object3 << object4;
  in.close();
  return 0;
}