首页 > 编程语言 > 详细

c++学习-运算符重载

时间:2015-06-20 23:26:41      阅读:304      评论:0      收藏:0      [点我收藏+]

 

#include <iostream>
using namespace std;

class num{
public:
    num(){n=new int;*n=1;cout<<"construct:"<<endl;}

    num(int x){n=new int;*n=x;cout<<"construct:"<<endl;}

    ~num(){delete n;n=NULL; cout<<"destruct:"<<endl;}

    //num(num &a){this->x=a.x;cout<<"copy:"<<x<<endl;}

    int getX(){
        return *n;
    }
    
    void setX(int x)
    {
        *n=x;
    }

    num operator=(num &r){
        cout<<"operator+"<<endl;
        *n=r.getX();
        return *this; //返回two的副本,two的副本返回后进行析构,导致n指向的内存释放
    }

private:
    int *n;

};

int & test(int & x)
{
    cout<<x<<endl;
    return x;
}

int main()
{
    
    num one,two,three;
    one.setX(110);
    two=one; //<==> two.operator =(one);
    

    cout<<two.getX()<<endl;
    

    return 0;

}

 

c++学习-运算符重载

原文:http://www.cnblogs.com/siqi/p/4591197.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!