深拷贝与浅拷贝

深拷贝与浅拷贝

程序默认情况下会自带浅拷贝,但是在对指针的拷贝时,在之后的析构环节容易引发重复清除堆区而导致程序崩溃。因此采用深拷贝来为指针重新申请一段堆区。

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

class Person
{
public:
	//默认构造函数
	Person()
	{
		cout << "Person类的默认构造函数" << endl;
	}
	//有参构造函数
	Person(int age, int height)
	{
		m_Height = new int(height);
		m_age = age;
		cout << "Person类的有参构造函数" << endl;
	}
	//拷贝构造函数_浅拷贝
	//Person(const Person& p2)
	//{
	//	m_age = p2.m_age;
	//	m_Height = p2.m_Height;
	//	cout << "Person类的浅拷贝构造函数" << endl;
	//}
	Person(const Person& p2)
	{
		m_age = p2.m_age;
		m_Height = new int(*p2.m_Height);
		cout << "这是深拷贝!" << endl;
	}
	~Person()
	{
		if (m_Height != NULL)
		{
			delete m_Height;
			m_Height = NULL;
		}
		cout << "Person类的析构函数" << endl;
	}
	int *m_Height; //使用一个指针来接收一块地址空间
	int m_age;
};

void test01()
{
	Person p1(18,160);
	Person p2(p1);
	cout << "p1的年龄为" << p1.m_age << "p1的身高为" << *p1.m_Height << endl;

	cout << "p2的年龄为" << p2.m_age << "p2的身高为" << *p2.m_Height << endl;

}

int main()
{
	test01();
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值