#?C++類的深拷貝與淺拷貝


```
#include<iostream>
using namespace std;
class Person
{
????public:
????Person()
????{
????????cout << "Person默認構(gòu)造函數(shù)調(diào)用" << endl;
????}
????Person(int age, int height)
????{
????????cout << "Person有參構(gòu)造函數(shù)調(diào)用" << endl;
????????m_Age = age;
????????m_Height = new int(height);
????}
Person(const Person & p)
{
????????cout << "Person拷貝構(gòu)造函數(shù)調(diào)用" << endl;
????? ? //m_Height = p.m_Height; 編譯器默認實現(xiàn)這個代碼
????????//深拷貝操作
????????m_Height = new int(*p.m_Height);//*p.m_Height 解引用,得到參數(shù)存儲的內(nèi)存地址
????}
//淺拷貝帶來堆區(qū)的重復(fù)釋放
~Person()
{ //析構(gòu)代碼, 將堆區(qū)開辟數(shù)據(jù)做釋放操作
????if (m_Height != NULL)
{
delete m_Height;
//放置野指針的出現(xiàn),先置空
m_Height = NULL;
}
????cout << "Person析構(gòu)函數(shù)調(diào)用" << 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的年齡為: " << p1.m_Age << "2身高為: " << *p1.m_Height << endl;
}
int main()
{
????test01();
????system("pause");
????return 0;
}
```