浅拷贝:简单的赋值拷贝操作
深拷贝:在堆区重新申请空间,进行拷贝工作
浅拷贝缺点用深拷贝来弥补
所以要再开辟一个堆
#include<iostream>
#include<cstring>
using namespace std;
class Person
{
public:
Person()
{
cout << "默认函数调用" << endl;
}
Person(int age,int height)
{
m_Height=new int(height);
m_Age = age;
cout << "有参函数调用" << endl;
}
~Person()
{
if (m_Height != NULL)
{
delete m_Height;
m_Height = NULL;
}
cout << "析构函数调用" << endl;
}
int m_Age;
int* m_Height;
Person(const Person& p)
{
cout << "拷贝构造函数调用" << endl;
m_Age = p.m_Age;
m_Height = new int(*p.m_Height);
}
};
void test01()
{
Person p1(18,160);
cout << "年龄" << p1.m_Age << "身高"<<*p1.m_Height<<endl;
Person p2(p1);
cout << "年龄" << p2.m_Age << "身高"<< *p2.m_Height << endl;
}
int main()
{
test01();
}
总结:如果属性有在堆区开辟的,一定要自己提供拷贝构造函数,防止浅拷贝带来的堆区内存重复释放 。