手撕构造函数、拷贝构造函数、赋值运算符重载、析构函数

class A
{
public:
    A(int n):m_n(n){
        m_ptr = new int(m_n);
    }
    A(const A& x){
        m_n = x.m_n;
        m_ptr = new int(m_n);
        memcpy(m_ptr, x.m_ptr, sizeof(int)*m_n);
    }
    A& operator=(const A& x){
        m_n = x.m_n;
        m_ptr = new int(m_n);
        memcpy(m_ptr, x.m_ptr, sizeof(int)*m_n);
        return *this;
    }//有返回值
    ~A(){
        delete m_ptr;
    }
public:
    int * m_ptr;
    int m_n;
};

int main()
{
    //-------------------对象方式-----------------
    A test0(10);//构造(函数)
    test0.m_ptr[0] = 1;
    A test1(test0);//拷贝构造(函数)
    cout << test1.m_ptr[0] << endl;
    A test2=test1;//运算符重载(函数)
    cout << test2.m_ptr[0] << endl;

    //----------------对象指针方式-----------------
    A* Test0=new A(10);//构造(函数)
    Test0->m_ptr[0] = 2;
    A* Test1 = new A(*Test0);//拷贝构造(函数)
    cout << Test1->m_ptr[0]<< endl;
    A Test2 = *Test1;//运算符重载(函数)
    cout << Test2.m_ptr[0] << endl;
    return 0;
}

 

posted @ 2018-08-23 14:44  aote369  阅读(188)  评论(0编辑  收藏  举报