C++/Overload/Extractor

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

Add a friend extractor for objects of type MyClass.

#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; 
  }
  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)
{
  cout << "Enter MyClassinates: ";
  stream >> ob.x >> ob.y;
  return stream;
}
int main()
{
  MyClass a(1, 1), b(10, 23);
  cout << a << b;
  cin >> a;
  cout << a;
  return 0;
}


Overload << and >>

>" src="http://www.java2s.com/Code/CppImages/Overloadand.PNG">


#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;
}


PhoneNumber extractor

#include <iostream>
#include <cstring>
using namespace std;
class PhoneNumber {
  char name[80];
  int areaCode;
  int prefix;
  int num;
public:
  PhoneNumber() { };
  PhoneNumber(char *n, int a, int p, int nm)
  {
    strcpy(name, n);
    areaCode = a;
    prefix = p;
    num = nm;
  }
  friend ostream &operator<<(ostream &stream, PhoneNumber o);
  friend istream &operator>>(istream &stream, PhoneNumber &o);
};
ostream &operator<<(ostream &stream, PhoneNumber o)
{
  stream << o.name << " ";
  stream << "(" << o.areaCode << ") ";
  stream << o.prefix << "-" << o.num << "\n";
  return stream; // must return stream
}
istream &operator>>(istream &stream, PhoneNumber &o)
{
  cout << "Enter name: ";
  stream >> o.name;
  cout << "Enter area code: ";
  stream >> o.areaCode;
  cout << "Enter prefix: ";
  stream >> o.prefix;
  cout << "Enter number: ";
  stream >> o.num;
  cout << "\n";
  return stream;
}
int main()
{
  PhoneNumber a;
  cin >> a;
  cout << a;
  return 0;
}