Overload ostream and istream operator : overload ostream istream operator « Operator Overloading « C++ Tutorial






#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

class MyClass {
  char name[80];
  char areacode[4];
  char prefix[4];
  char num[5];
public:
  MyClass() { };
  MyClass(char *n, char *a, char *p, char *nm)
  {
    strcpy(name, n);
    strcpy(areacode, a);
    strcpy(prefix, p);
    strcpy(num, nm);
  }
  friend ostream &operator<<(ostream &stream, MyClass o);
  friend istream &operator>>(istream &stream, MyClass &o);
};

// Display name and phone number.
ostream &operator<<(ostream &stream, MyClass o)
{
  stream << o.name << " ";
  stream << "(" << o.areacode << ") ";
  stream << o.prefix << "-";
  stream << o.num << "\n";
  return stream; // must return stream
}

// Input name and telephone number.
istream &operator>>(istream &stream, MyClass &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()
{
  MyClass a;
  char c;

  fstream pb("phone", ios::in | ios::out | ios::app);

  if(!pb) {
    cout << "Cannot open phone book file.\n";
    return 1;
  }

  cin >> a;
  pb << a;    // write to disk

  char ch;
  pb.seekg(0, ios::beg);
  while(!pb.eof()) {
    pb.get(ch);
    if(!pb.eof()) cout << ch;
 }
 pb.clear();  // reset eof
 cout << endl;
 pb.close();

}
Cannot open phone book file.








10.15.overload ostream istream operator
10.15.1.Class level ostream operator and istream operator
10.15.2.istream operator with data check
10.15.3.Class ostream operator
10.15.4.ostream and istream operator for a class
10.15.5.Complex logic in ostream operator
10.15.6.friend ostream operator for private fields
10.15.7.Overload ostream and istream operator
10.15.8.Ignore: manipulator that ignores N lines
10.15.9.Overloading >>: To demonstrate a custom inserter, one will be created for objects of type phonebook, shown here.
10.15.10.Overload << (inserter)