码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-01-24 12:55:09      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

 
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;
}      

 

 

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

标签:

原文地址:http://www.cnblogs.com/XingyingLiu/p/5154871.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!