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");
}

 

转载于:https://www.cnblogs.com/kexb/p/5526736.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值