Linux安全网 - Linux操作系统_Linux 命令_Linux教程_Linux黑客

会员投稿 投稿指南 本期推荐:
搜索:
您的位置: Linux安全网 > Linux编程 > » 正文

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

来源: 未知 分享至:

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

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)

 


Tags:
分享至:
最新图文资讯
1 2 3 4 5 6
验证码:点击我更换图片 理智评论文明上网,拒绝恶意谩骂 用户名:
关于我们 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 发展历史