C++ 深拷贝与浅拷贝

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


class Person {

	
public:

	Person() {
		cout << "Person的无参构造函数调用" << endl;
	};

	Person(int age) {
		m_Age = age;
		cout << "Person的有参构造函数调用" << endl;
	};



	//拷贝构造函数
	Person(const Person &p) {
		cout << "Person的拷贝构造函数调用" << endl;
		//将传入的人身上的所有属性,拷贝到我身上
		m_Age = p.m_Age;
		//	m_Age = p.m_Age;
	};

	~Person() {

		cout << "Person的析构函数调用" << endl;
	}

	int m_Age;

};


void test() {


	//1.括号法
	Person p1; //默认构造函数调用
	Person p2(10); //有参构造函数
	Person p3(p2); //拷贝构造函数

	//2、显示法
	//3、隐式转换法


}


//1、使用一个已经创建完毕的对象来初始化- -个新对象
void test01() {
	

	Person p1(18);
	cout << "p1的年龄为:" << p1.m_Age << endl;
	Person p2(p1);
	cout << "p2的年龄为:"<< p2.m_Age << endl;


};

//2、值传递的方式给函数参数传值
void doWork(Person p) {
}
void test02() {
	Person p;
	doWork(p);
}

int main() {
	test01();

	//	test01();
	system("pause");

}

 

 

 

深拷贝解决浅拷贝的堆内存重复释放问题

//自己实现拷贝构造函数解决浅拷贝带来的问题
	Person(const Person &p) {   //拷贝构造函数编译器默认实现
		cout << "Person 拷贝构造函数调用" << endl;
		m_Age = p.m_Age;
	//	m_Height = p.m_Height;  //拷贝构造函数编译器默认实现

		//深拷贝操作  解决浅拷贝堆内存重复释放
		m_Height = new int(*p.m_Height);
	}

 

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


class Person {


public:

	Person() {
		cout << "Person的无参构造函数调用" << endl;
	};

	Person(int age, int height) {
		m_Age = age;
		cout << "Person的有参构造函数调用" << endl;

		m_Height = new  int(height);

	};


	
	/*Person(const Person &p){   //拷贝构造函数编译器默认实现
		cout << "Person 拷贝构造函数调用"<< endl;
		m_Age = p.m_Age;
		m_Height = p.m_Height;  //
	}
	*/

	//自己实现拷贝构造函数解决浅拷贝带来的问题
	Person(const Person &p) {   //拷贝构造函数编译器默认实现
		cout << "Person 拷贝构造函数调用" << endl;
		m_Age = p.m_Age;
	//	m_Height = p.m_Height;  //拷贝构造函数编译器默认实现

		//深拷贝操作  解决浅拷贝堆内存重复释放
		m_Height = new int(*p.m_Height);
	}



	//拷贝构造函数编译器默认实现
	/*Person(const Person &p) {
		cout << "Person的拷贝构造函数调用" << endl;
		//将传入的人身上的所有属性,拷贝到我身上
		m_Age = p.m_Age;
		//	m_Age = p.m_Age;
	};
*/
	~Person() {
		if (m_Height != NULL) {
			delete m_Height;
			m_Height = NULL;
		}

		cout << "Person的析构函数调用" << endl;
	}

	int m_Age;


	int *m_Height;   //身高
};




//1、使用一个已经创建完毕的对象来初始化- -个新对象
void test01() {
	

	Person p1(18,160);
	cout << "p1的年龄为:" << p1.m_Age << "身高为:"<< *p1. m_Height << endl;
	Person p2(p1);
	cout << "p2的年龄为:" << p2.m_Age << "身高为:" << *p2.m_Height << endl;


};

//2、值传递的方式给函数参数传值
void doWork(Person p) {
}
void test02() {
	Person p;
	doWork(p);
}

int main() {
	test01();

	//	test01();
	system("pause");

}

 

总结:如果属性有在堆区开辟的,一定要自己提供拷贝构造函数,防止浅拷贝带来的问题

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值