You are here

Overloading of input/output operators

Operators are not necessarily member functions, but can be created as global functions, whereas an output operator has a reference to an ostream (or basic_ostream) and a reference to a variable as input parameters and returns itself. Input operators are similarly created.
Example:
  std::ostream& operator << (std::ostream&, CString&);
  std::istream& operator >> (std::istream&, std::stream&);

Ostream and istream are already overloaded for the standard data types. If you want to define your own operators, you should first try to trace the data type back to one of the standard data types.
Example:

  std::ostream& operator << (std::ostream& ostr, CString& cstr)
  {
    return(ostr << (LPTCSTR) cstr);
  }

As last resort you can trace back every data type to char. But you can use the methods istream::get(), istream::getline() and ostream::put as well.

You must regard the data access rights when you declare operators. When you plan to input and output non public member data, than you must declare the operator as friend in the declaration of your member class.
Considering the operators
  std::ostream& operator << (std::ostream&, CString&);
  std::ostream& operator << (std::ostream&, std::string&);

  std::ostream& operator << (std::ostream& ostr, CString& cstr)
  {
    return(ostr << (LPTCSTR) cstr);
  }

  std::ostream& operator << (std::ostream& ostr, std::string& sstr)
  {
    return(ostr << sstr.c_str());
  }
the following example results:

  OG_constream text_fenster;

  int i = 10;
  double d = 3.14156;
  std::string sstr("STL String");
  CString cstr("Microsoft CString");

  text_fenster << "i = " << i << std::endl;
  text_fenster << "d = " << d << std::endl;
  text_fenster << "STL String = " << sstr << std::endl;
  text_fenster << "Microsoft CString = " << cstr << std::endl;