C++深拷贝与浅拷贝

 一.代码

#include <iostream>
using namespace std;

class person {
public:
	person() {

	}
	person(int age,int hight) {
		cout << "有参构造" << endl;
		m_age = age;
		m_hight = new int(hight);
	}
	person(const person& p) {
		cout << "拷贝构造" << endl;
		m_age = p.m_age;
		m_hight = new int(*p.m_hight);
	}

	~person() {
		cout << "析构函数" << endl;
		if (m_hight != NULL) {
			delete m_hight;
			m_hight = NULL;
		}
	}
	int m_age;
	int* m_hight;
};

void test01() {
	person p1(18,160);

	cout << "p1的年龄为:" << p1.m_age << "p1的身高为: " << *p1.m_hight << endl;
	person p2(p1);

	cout << "p2的年龄为:" << p2.m_age << "p2的身高为: " << *p2.m_hight << endl;
}


int main() {
	test01();
	return 0;
}

二.解析

拷贝构造函数,是一种特殊的构造函数,它在创建对象时,是使用同一类中之前创建的对象来初始化新创建的对象。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值