#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;
}
Person(const Person &p)
{
cout << "Person拷貝建構式呼叫" << endl;
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 << "Person解構式呼叫" << endl;
}
int m_Age;
int *m_Height;
};
void test501()
{
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()
{
test501();
system("pause");
return 0;
}
語法能編譯成功,逐條除錯也能列印。當就是記憶體報錯
uj5u.com熱心網友回復:
代碼沒有問題,請重新編譯uj5u.com熱心網友回復:
你這很清楚了啊,默認拷貝就是把指標賦給了新物件,深拷貝需要重新申請記憶體,再把這個地址賦給新物件轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/42717.html
標籤:C++ 語言
