浅拷贝:简单的赋值拷贝操作
深拷贝:在堆区重新申请空间,进行拷贝
解决了浅拷贝重复释放空间的问题。
例子如下:
#include<iostream>
using namespace std;
#include<string>
#include <fstream>
class Person
{
public:
Person()
{
cout << "构造函数调用" << endl;
}
Person(int age,int helight)
{
m_Age = age;
m_Helight = new int(helight);
cout << "有参构造函数调用" << endl;
}
Person(const Person& p)
{
m_Age = p.m_Age;
m_Helight = new int (*p.m_Helight);//堆区重新创建空间
cout << "Person深拷贝构造函数调用" << endl;
}
~Person()
{
if (m_Helight!= NULL)
{
delete m_Helight;
m_Helight = NULL;
}
cout << "析构函数调用" << endl;
}
int m_Age;
int *m_Helight;
};
void test01()
{
Person p1(18,160);
Person p2(p1);
cout << "p1的年龄是:" << p1.m_Age <<"p1身高"<<*p1.m_Helight<< endl;
cout << "p2的年龄是:" << p2.m_Age << "p2身高" << *p2.m_Helight << endl;
}
int main()
{
test01();
system("pause");
return 0;
}