Overload << and >> : Extractor « Overload « C++






Overload << and >>

Overload << and >>

#include <iostream>
using namespace std;

class MyClass {
  int x, y; 
public:
  MyClass() { 
     x=0; 
     y=0; 
  }
  MyClass(int i, int j) { 
     x=i; 
     y=j; 
  }
  void getXY(int &i, int &j) { 
     i=x; 
     j=y; 
  }
  MyClass operator<<(int i);
  MyClass operator>>(int i);
};

// Overload <<.
MyClass MyClass::operator<<(int i)
{
  MyClass temp;

  temp.x = x << i;
  temp.y = y << i;

  return temp;
}

// Overload >>.
MyClass MyClass::operator>>(int i)
{
  MyClass temp;

  temp.x = x >> i;
  temp.y = y >> i;

  return temp;
}

int main()
{
  MyClass object1(4, 4), object2;
  int x, y;
 
  object2 = object1 << 2;  // ob << int
  object2.getXY(x, y);
  cout << "(object1<<2) X: " << x << ", Y: " << y << endl;

  object2 = object1 >> 2; // ob >> int
  object2.getXY(x, y);
  cout << "(object1>>2) X: " << x << ", Y: " << y << endl;

  return 0;
}


           
       








Related examples in the same category

1.Add a friend extractor for objects of type MyClass.Add a friend extractor for objects of type MyClass.
2.PhoneNumber extractorPhoneNumber extractor