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

时间:2016-01-24 12:53:43   收藏:0   阅读:359

https://www.coursera.org/learn/cpp-chengxu-sheji/lecture/c3tbl/liu-cha-ru-yun-suan-fu-he-liu-ti-qu-yun-suan-fu-de-zhong-zai  笔记

 

 
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
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!