浅拷贝与深拷贝

浅拷贝代码示例

#include<iostream>
#include<string>
using namespace std;

class Student {
public:

	int m_age;
    //构造函数传入年龄值
	Student(int a) {
		m_age = a;
	}
};

int main() {
	Student p1(18);
	Student p2(p1);//利用默认拷贝构造函数实现浅拷贝
	cout << "p1的年龄为: " << p1.m_age << endl;
	cout << "p2的年龄为: " << p2.m_age << endl;

	system("pause");
	return 0;
}

此时完成了浅拷贝,将p1拷贝给了p2 ,下面我们添加一个指针成员变量身高,再次进行拷贝

#include<iostream>
#include<string>
using namespace std;

class Student {
public:

	int m_age;
	int* m_height;
    //构造函数传入年龄值和身高值
	Student(int a,int b) {
		m_age = a;
		m_height = new int(b);
		//在堆区new一个地址来存放身高,用m_height接收
	}
    //我们在构造函数中使用new在堆区开辟了一个地址所以需要手动编写析构函数释放
	~Student() {
		delete m_height;
	}
};

int main() {
	Student p1(18,180);
	Student p2(p1);
	cout << "p1的年龄为: " << p1.m_age << " p1的身高为: " << *p1.m_height << endl;
	cout << "p2的年龄为: " << p2.m_age << " p2的身高为: " << *p1.m_height << endl;
	system("pause");
	return 0;
}

 此时系统崩溃,是由于浅拷贝两个对象的只进行了值传递,而身高共用一个地址,delete释放同一个地址两次导致崩溃,所以我们需要深拷贝,拷贝指针变量时新开辟地址。

#include<iostream>
#include<string>
using namespace std;

class Student {
public:

	int m_age;
	int* m_height;
    //构造函数传入年龄值和身高值
	Student(int a,int b) {
		m_age = a;
		m_height = new int(b);
		//在堆区new一个地址来存放身高,用m_height接收
	}
    //我们在构造函数中使用new在堆区开辟了一个地址所以需要手动编写析构函数释放
	~Student() {
		delete m_height;
	}

	//深拷贝构造函数
	Student(const Student& p) {
		m_age = p.m_age;
		//m_height = p.m_height;(默认浅拷贝构造函数,只拷贝值)
		m_height = new int(*p.m_height);
	}
};

int main() {
	Student p1(18,180);
	Student p2(p1);//用新的拷贝构造函数进行深拷贝
	cout << "p1的年龄为: " << p1.m_age << " p1的身高为: " << *p1.m_height << endl;
	cout << "p2的年龄为: " << p2.m_age << " p2的身高为: " << *p1.m_height << endl;
	system("pause");
	return 0;
}

 

 ok,程序运行成功,没有报错!

 

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值