C++(OOP)深复制、浅复制

在这里插入图片描述
案例

#include <iostream>
#include <string.h>

using namespace std;

class Demo
{
public:
	Demo(int pa, char *cstr)
	{
		this->a = pa;
		this->str = new char[1024];
		strcpy(this->str, cstr);
	}
public:
	int a;
	char *str;
};

int main()
{
	Demo A(10, "hello");

	Demo B = A; // 复制
	cout << "复制结果:" << endl;
	cout << A.a << " " << A.str << endl;
	cout << B.a << " " << B.str << endl;

	B.a = 8;  // 只修改了B
	B.str[0] = 'k';
	
	cout << endl;
	cout << "只修改了B:" << endl;
	cout << A.a << " " << A.str << endl;
	cout << B.a << " " << B.str << endl;

	return 0;
}

运行结果:

复制结果:
10 hello
10 hello

只修改了B:
10 kello
8 kello

A居然也被修改了,这就是浅拷贝(浅复制)引起的
很多时候出现这种情况,是我们不愿意看到的,所以我们要用深拷贝(深复制)

#include <iostream>
#include <string.h>

using namespace std;

class Demo
{
public:
	Demo(int pa, char *cstr)
	{
		this->a = pa;
		this->str = new char[1024];
		strcpy(this->str, cstr);
	}

	// 创建复制构造函数
	Demo(Demo &obj)
	{
		this->a = obj.a;
		// 深拷贝 创建新的指针
		this->str = new char[1024];
		if (str != 0)
			strcpy(this->str, obj.str);
	}

	// 析构函数 消除指针
	~Demo()
	{
		delete str;
	}

public:
	int a;
	char *str;
};

int main()
{
	Demo A(10, "hello");

	Demo B = A; // 复制
	cout << "复制结果:" << endl;
	cout << "A: " <<  A.a << " " << A.str << endl;
	cout << "B: " << B.a << " " << B.str << endl;

	B.a = 8;  // 只修改了B
	B.str[0] = 'k';
	cout << endl;

	cout << "只修改了B:" << endl;
	cout << "A: " <<  A.a << " " << A.str << endl;
	cout << "B: " << B.a << " " << B.str << endl;

	return 0;
}

运行结果:

复制结果:
A: 10 hello
B: 10 hello

只修改了B:
A: 10 hello
B: 8 kello
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值