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

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

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)

 

转载于:https://www.cnblogs.com/liangyan19910818/archive/2011/10/22/2221110.html

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值