对象特性---->深拷贝与浅拷贝
生活随笔
收集整理的這篇文章主要介紹了
对象特性---->深拷贝与浅拷贝
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
淺拷貝:簡單的賦值拷貝操作。
深拷貝:在堆區(qū)申請一塊空間,進行拷貝操作。
淺拷貝:編譯器提供的拷貝構(gòu)造函數(shù)對傳入值進行賦值拷貝操作
#include<iostream>
using namespace std;class Person
{
public:Person(){cout << "Person無參構(gòu)造函數(shù)的調(diào)用" << endl;}Person(int age){cout << "Person有參構(gòu)造函數(shù)的調(diào)用" << endl;m_Age = age;}~Person(){cout << "Person析構(gòu)函數(shù)的調(diào)用" << endl;}int m_Age;
};void test01()
{Person p1(18);cout << "p1的年齡是: " << p1.m_Age << endl;Person p2(p1);cout << "p2的年齡是: " << p2.m_Age << endl;
}int main()
{test01();system("pause");return 0;
}
上述代碼類中我們沒有寫入拷貝構(gòu)造函數(shù),但是運行毫無問題,這是編譯器為我們提供了拷貝構(gòu)造函數(shù),并且我們稱這種拷貝為淺拷貝;
深拷貝:在堆區(qū)申請一塊空間,進行拷貝操作。
#include<iostream>
using namespace std;class Person
{
public:Person(){cout << "Person無參構(gòu)造函數(shù)的調(diào)用" << endl;}Person(int age,int height){m_Age = age;m_Height = new int(height);cout << "Person有參構(gòu)造函數(shù)的調(diào)用" << endl;}~Person(){if (m_Height != NULL) //標(biāo)準(zhǔn)的對堆區(qū)空間釋放的一個格式{delete m_Height;m_Height = NULL;}cout << "Person析構(gòu)函數(shù)的調(diào)用" << endl;}int m_Age;int* m_Height; //這塊為什么要把類型寫為int*呢,因為堆區(qū)申請的空間為空間首地址
}; //s所以拿指針來接收void test01()
{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()
{test01();system("pause");return 0;
}
重點:上述代碼中的int* m_Height為什么要將類型寫為int*呢? ?因為堆區(qū)申請的空間為空間首地址,所以得拿指針來接收
但是很不幸的是 上述代碼會報錯:
?錯誤原因就是:其中0x112233只是舉個例子而已,并不是說地址真的是0x112233
因為編譯器所給出的拷貝構(gòu)造函數(shù)如下圖,所以會出現(xiàn)重復(fù)釋放內(nèi)存而報錯的情況?
Person(const Person& p)
{cout << "Person拷貝構(gòu)造函數(shù)的調(diào)用" << endl;m_Age = p.m_Age;m_Height = p.m_Height; //如果用編譯器給的拷貝構(gòu)造函數(shù)就是這樣的底層邏輯
}
正確的拷貝構(gòu)造函數(shù):
Person(const Person& p)
{cout << "Person拷貝構(gòu)造函數(shù)的調(diào)用" << endl;m_Age = p.m_Age;m_Height = new int(*p.m_Height);
}
原理如下:
?這就是深拷貝的原理。
深拷貝所有代碼如下:
#include<iostream>
using namespace std;class Person
{
public:Person(){cout << "Person無參構(gòu)造函數(shù)的調(diào)用" << endl;}Person(int age,int height){m_Age = age;m_Height = new int(height);cout << "Person有參構(gòu)造函數(shù)的調(diào)用" << endl;}Person(const Person& p){cout << "Person拷貝構(gòu)造函數(shù)的調(diào)用" << endl;m_Age = p.m_Age;m_Height = new int(*p.m_Height);}~Person(){if (m_Height != NULL){delete m_Height;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的年齡是: " << p2.m_Age << "身高為: " << *p2.m_Height << endl;
}int main()
{test01();system("pause");return 0;
}
代碼這東西? 真的是三天不敲手生了? 一周不敲可能連頭文件都能寫錯了,所以兄弟們記得每天練習(xí)!!!沖沖沖!!!
撐不住的時候,可以對自己說聲“我好累”,永遠(yuǎn)不要在心里承認(rèn)說“我不行”。
總結(jié)
以上是生活随笔為你收集整理的对象特性---->深拷贝与浅拷贝的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 对象特性--构造函数调用规则
- 下一篇: 竹子多少钱啊?