c++(重载等号=操作为深拷贝)

// ConsoleApplication19.cpp : 定义控制台应用程序的入口点。
//
#pragma warning(disable:4996)
#include "stdafx.h"
using namespace std;
#include <iostream>

class A {
public:

    //=等号操作默认的是浅拷贝 这里重载=为深拷贝 当类里出现指针变量 用等号是浅拷贝
    A& operator=(A& obj) 
    {
        if (this->pc != NULL) 
        {
            this->a = 0;
            delete this->pc;
        }
        this->a = obj.a;
        this->pc = new char[obj.a];
        return *this;
    }
    A() {}
    A(int a) 
    {
        this->a = a;
        this->pc = new char[a];
    }

    ~A() 
    {
        if (this->pc != NULL) 
        {
            delete pc;
        }
        cout << "A析构函数"<< endl;
    }
private:
    int a;
    char * pc;
};

class B {
public:
    B()
    {
    
    }

private:
    int b1;
    int b2;
    A a1;
    A a2;


};

void displayObj() 
{
    A a1(1);
    A a2;

    a2 = a1;


}
void main()
{
    displayObj();

    system("pause");
}

 

posted on 2016-05-25 13:49  听哥哥的话  阅读(2657)  评论(0编辑  收藏  举报

导航