码迷,mamicode.com
首页 > 编程语言 > 详细

c++学习-运算符重载

时间:2015-06-20 23:29:40      阅读:235      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!