流插入运算符为什么要被重载为全局函数?

 
Part 1. 流插入运算符的重载:
 
cout<<5<<endl;
 
cout是在iosream中定义的一个ostream对象
iostream中对“<<”进行了重载。  cout<<5; 即 cout.operator<<(5);
 
iostream中对"<<"的重载函数:
ostream & ostream::operator<<(int n){
     ……//输出n的代码
     return *this; // *this 就是cout
}

 

Part 2. 流插入运算符为什么要被重载为全局函数
 
假设有Complex对象c, 如果要用cout<<c来输出, 就要对“<<“重载。
但是1)不能在ostream类中对"<<"重载,因为ostream类已经被封装好了。
  2)不能在Complex类中对"<<"重载,否则*this对象会混淆。 
class Complex
{
    public:
        int a,b;
};

ostream &operator<<(ostream &os, Complex &x){  //cout<<x<<endl;
    os<<x.a<<"+i"<<x.b;   
    // the "os<<x.a" is os.operator<<(x.a);
    // and in the definition of os.operator<<(), it should returned *this
    // which represents a ostream object 
    return os;
}      

 

 

转载于:https://www.cnblogs.com/XingyingLiu/p/5154871.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值