next up previous
Next: ifstream and ofstream methods Up: The ostream, istream, ofstream Previous: Formatting with ANSI C

Handling new datatypes with cin, cout, and cerr

This section describes more advanced material. It can be skipped without losing continuity.

If we want to read and write our custom types using cin and cout, we can overload the operators << and >> in conjunction with the istream and ostream classes.

To read and write our complex numbers, we add two functions and make them friends to our complex class:



#include <iostream>
using namespace std;

template<class T>
class complex {
public:
  T re;
  T im;

  template<class U>
  friend ostream & operator<<(ostream &, complex<U>&);

  template<class U>
  friend istream & operator>>(istream &, complex<U>&);
};

template<class U>
ostream & operator<<(ostream &s, complex<U> &z){
  s << z.re << " + I * " << z.im;
  return s;
}
template<class U>
istream & operator>>(istream &s, complex<U> &z){
  s >> z.re >> z.im;
  return s;
}

typedef complex<double> dcmplx;

int main(){
   dcmplx a;

   cout << "Enter Re and Im\n";
   cin >> a;
   cout << "Your number is " << a << "\n";
}

Let's examine one of these new subprograms to see how it works:




template<class U>
ostream & operator<<(ostream &s, complex<U> &z){
  s << z.re << " + I * " << z.im;
  return s;
}

To understand the concept, think of the console output as a long stream of characters. This operator appends a character string representation of the complex number to the end of this stream.

This definition overloads the left-shift operator << so it can handle a new pair of arguments: the first, a reference to a member of the ostream class and the second, a reference to one of the complex number variants.

This operator is called when we write cout << a with a one of the complex number variants. In that case s becomes another name for cout. So in effect the function simply does |cout « z.re « " + I * " « z.im|, which uses << with just scalar values that the class already knows how to handle. The operator appends a a character string translation of our number to the stream. We must return the modified stream so the operator can be chained as in cout << a << b.


next up previous
Next: ifstream and ofstream methods Up: The ostream, istream, ofstream Previous: Formatting with ANSI C
Carleton DeTar 2008-11-10