1、浅拷贝:简单的复制拷贝操作
(可能会使堆区的内存被重复释放)
2、深拷贝:在堆区重新申请空间,进行拷贝操作
【自己实现拷贝构造函数,解决浅拷贝带来的问题 自己在堆区申请一块内存,使得p1和p2指向不同的内存不同(深拷贝)】
#include<iostream>
using namespace std;
class Person
{
public:
Person()
{
cout << "person 的默认构造函数调用" << endl;
}
Person(int age,int height)
{
m_Age = age;
m_Height = new int(height);
cout << "person 的有参构造函数调用" << endl;
}
//自己实现拷贝构造函数,解决浅拷贝带来的问题 自己在堆区申请一块内存,使得p1和p2指向不同的内存不同(深拷贝)
Person(const Person &p)
{
cout << "person 的拷贝构造函数调用" << endl;
m_Age = p.m_Age;
//m_Height = new int(height);编译器默认实现此行代码
m_Height = new int(*p.m_Height); //深拷贝 在堆区开辟一块内存
}
~Person()
{
//析构代码,将堆区开辟的数据做释放操作
if (m_Height != NULL)
{
delete m_Height;
m_Height = NULL;
}
cout << "person 的析构构造函数调用" << endl;
}
int m_Age;
int *m_Height;
};
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;
}
int main()
{
test01();
return 0;
}