重载流插入运算符和流提取运算符

对"<<"和">>"重载的函数形式如下

istream& operator >> (istream & , 自定义类 &) ;

ostream& operator << (ostream & , 自定义类 &) ;

只能将重载">>"和"<<"函数作为友元函数或普通函数,而不能将它们定义为成员函数

 1 #include <iostream.h>
2
3 //using namespace std;
4
5 class Complex
6 {
7 public:
8 friend ostream& operator<< (ostream& , Complex&);
9 friend istream& operator>> (istream& , Complex&);
10 private:
11 double real;
12 double imag;
13 };
14
15 ostream& operator<< (ostream& output , Complex& c)
16 {
17 output << "(" << c.real ;
18 if(c.imag >= 0) output << "+" ;
19 output << c.imag << "i)" << endl;
20 return output ;
21 }
22
23 istream& operator>> (istream& input , Complex& c)
24 {
25 cout << "please input real part and imaginary part of complex number:";
26 input >> c.real >> c.imag ;
27 return input;
28 }
29
30 int main(void)
31 {
32 Complex c1 , c2 ;
33 cin >> c1 >> c2 ;
34 cout << "c1 = " << c1 << endl;
35 cout << "c2 = " << c2 << endl;
36 return 0 ;
37 }

 

编译系统把 "cout << c"解释为:

operator << (cout , c)

即以把cout 和 c 作为实参 ,调用下面的operator<< 函数

ostream& operator<< (ostream& output , Complex& c)

 

posted @ 2011-10-22 13:12  MATRIX | yan  阅读(2491)  评论(0编辑  收藏  举报