self-confidence,the source of all the power

导航

C++ 流操作符重载函数

1. 问题

  在C++中,在进行输入输出操作时,我们首先会想到用cout, cin这两个库操作语句来实现,比如

    cout << 8 << "hello world!" << endl;

    cin >> s;

  cout,cin分别是库ostream, istream里的类对象

  如果想要cout,cin来输出或输入一个类对象,这样的需求它能满足吗?很显然,原来的cout不太可能满足直接输入输出一个我们自定义的类对象,

  但是只要我们对<<, >>操作符进行重载就可以让它处理自定义的类对象了。

2. 实现

  有一复数类:

class Complex {
     priate:
           int real;
           int imag;
     public:
           Complex(int r=0, int i=0):real(r),imag(i) {
                  cout << real << " + " << imag << "i" ;
                  cout << "complex class constructed."
           } 
}

int main() {
      Complex c; // output : 0+0i, complex class constructed.
      cout << c ; // error

      return 0;
}

  之所以上面main函数中 cout << c会出错,是因为 cout本身不支持类对象的处理,如果要让它同样能打印类对象,必须得重载操作符<<.

#include <iostream>
#include <string>

class Complex {
     priate:
           int real;
           int imag;
     public:
           Complex(int r=0, int i=0):real(r),imag(i) {
                  cout << real << " + " << imag << "i" ;
                  cout << "complex class constructed."
           } 
           // overload global function
           friend ostream & operator<<(ostream & o, const Complex & c);
           friend istream & operator >> (istream & i, Complex & c);
}

ostream & operator<<(ostream & o, const Complex & c) {
        o<< c.real << "+" << c.imag << "i";
        return o;
}

istream & operator >> (istream & i, Complex & c){
       string  s;
       i >> s;   // simillar to cin >> s; input string format like as a+bi
       ...  // parse s and get the real and imag
       c. real = real;
       c.imag = imag;
       return i;
}

  重载了操作符 <<, >> 运算后, 就可以对类Complex直接进行 输入输出操作了,比如

int main{
       Complex c, c1;
       cin >> c;   //input : 3+4i
       cout << c <<";" << c1 << " complex output."; // output : 3+4i; 0+0i complex output.
}

 

posted on 2014-11-02 17:22  漩涡鸣人  阅读(1683)  评论(0编辑  收藏  举报