浅拷贝:简单的赋值拷贝操作
深拷贝:在堆区重新申请空间,进行拷贝操作
#include<iostream>
using namespace std;
class Person
{
public:
Person()
{
cout << "无参构造调用" << endl;
}
Person(int age,int height)
{
m_Age = age;
m_Height = new int(height);
cout << "有参构造调用" << endl;
}
//自己实现拷贝构造
Person(const Person &p)
{
m_Age = p.m_Age;
//m_Height =p.m_Height; 这行是编译器默认实现的代码,是浅拷贝
//下面是深拷贝
m_Height =new int(*p.m_Height);
}
~Person()
{
if (m_Height != NULL)
{
delete m_Height;
m_Height == NULL;
}
cout << "析构函数调用" << endl;
}
int m_Age;
int *m_Height;
};
void test01()
{
Person p1(18,160);
Person p2(p1);
cout << "p1的年龄和身高:" << p1.m_Age <<","<<*p1.m_Height<< endl;
cout << "p2的年龄和身高:" << p2.m_Age << "," << *p2.m_Height << endl;
}
void main()
{
test01();
system("pause");
}
下图是浅拷贝带来的问题
下面是深拷贝解决堆区重复释放问题
https://www.bilibili.com/video/BV1et411b73Z?p=110