• 深入C++的运算符重载


    对于简单的运算符,可以参考之前的博文。之后会有一篇关于从等号运算符重载的角度研究深浅拷贝的博文。

    逗号运算符重载

    逗号运算符重载需要一个参数,并且返回自身类。逗号运算符在复制操作中比较常见,下面就是以赋值操作为例的逗号运算符重载。

    #include<string>
    #include<iostream>
    using namespace std;
    class Tem{
        private:
            int x;
        public:
            Tem(int);
            Tem operator ,(Tem);
            void display();
    }; 
    
    Tem::Tem(int xx=0){
        x = xx;
    }
    
    Tem Tem::operator , (Tem t){
        cout<<t.x<<endl;
        return Tem(t.x);
    }
    void Tem::display(){
        cout<<"Class(Tem) includes of: "<<x<<endl;
    }
    
    int main(){
        
        Tem tem1(10);
        Tem tem2(20);
        Tem other = (tem1,tem2); //会选择第二个 int a= 1,2;a等于2而不是1 
        other.display();
        
        return 0;
    }

    取成员运算符重载

    返回类类型的指针变量,符合平时的用法,这样就可以不用在声明变量时候使用指针,但是之后可以按照指针的方式调用,简单方便。

    #include<iostream>
    using namespace std;
    
    class Tem{
        public:
            int n;
            float m;
            Tem* operator ->(){
                return this;
            }
    }; 
    int main(){
        Tem tem;
        tem->m = 10; //调用->运算符,返回Tem*类型并访问m 
        cout<<"tem.m is "<<tem.m<<endl;
        cout<<"tem->m is "<<tem->m<<endl;
        return 0;
    }

    输入输出运算符重载

    >>,<<运算符重载分别在cin、cout之后调用。我们需要用友元运算符对他们进行重载,注意返回类型分别是istream 和 ostream。

    #include<iostream>
    using namespace std;
    
    class Date{
        private:
            int year,month,day;
        public:
            Date (int y,int m,int d){
                year = y;
                month = m;
                day  = d;
            }
            friend ostream& operator <<(ostream &stream,const Date &date){
                stream<<date.year<<" "<<date.month<<" "<<date.day<<endl;
                return stream;
            }
            friend istream& operator >>(istream &stream,Date &date){
                stream>>date.year>>date.month>>date.day;
                return stream;
            }
    }; 
    int main(){
        Date _date(2017,6,13);
        cout<<_date;
        cin>>_date;
        cout<<_date;
        return 0;
    }

    欢迎进一步交流本博文相关内容:

    博客园地址 : http://www.cnblogs.com/AsuraDong/

    CSDN地址 : http://blog.csdn.net/asuradong

    也可以致信进行交流 : xiaochiyijiu@163.com 

    欢迎转载 , 但请指明出处  :  )


  • 相关阅读:
    HDU 1425:sort
    HDU 1021:Fibonacci Again
    HDU 2035:人见人爱A^B
    HDU 1061:Rightmost Digit
    HDU 1005:Number Sequence
    HDU 1008:Elevator
    HDU 1004:Let the Balloon Rise
    HDU 2018:母牛的故事
    java推荐书籍及下载
    VC6.0 快捷键
  • 原文地址:https://www.cnblogs.com/zhangyubao/p/7003560.html
Copyright © 2020-2023  润新知