[C++基礎]021_淺拷貝和深拷貝

來源:互聯網
上載者:User

淺拷貝:即類中有指標成員變數,拷貝時,只拷貝了指標變數,而沒有拷貝指標變數所指向的地址塊。

執行個體代碼:

 1 #include <iostream> 2 using namespace std; 3  4 class Tree{ 5 public: 6     // 拷貝建構函式 7     Tree(const Tree& tree){ 8         this->num = tree.num; 9     }10     // 建構函式11     Tree(){12         num = new int(10);13     }14     // 解構函式15     ~Tree(){16         delete num;17     }18     // 普通列印成員變數內容函數19     void printNum(){20         cout<<*(this->num)<<endl;21     }22 private:23     int *num;24 };25 26 int main(){27     // 在堆裡產生一個對象28     Tree *tree1 = new Tree();29     tree1->printNum();30 31     // 拷貝建構函式起作用了32     Tree tree2(*tree1);33     tree2.printNum();34     35     // 銷毀tree1對象36     delete tree1;37     // 此時,num是懸null 指標了38     tree2.printNum();39 40     system("pause");41     return 0;42 }

 

深拷貝:即複製對象時如有指標變數,那麼也複製指標變數所指向的記憶體塊。

執行個體代碼:

 1 #include <iostream> 2 using namespace std; 3  4 class Tree{ 5 public: 6     // 拷貝建構函式(深拷貝) 7     Tree(const Tree& tree){ 8         this->num = new int(); 9         *(this->num) = *(tree.num);10     }11     // 建構函式12     Tree(){13         num = new int(10);14     }15     // 解構函式16     ~Tree(){17         delete num;18     }19     // 普通列印成員變數內容函數20     void printNum(){21         cout<<*(this->num)<<endl;22     }23 public:// 這裡為了方便,將成員變數聲明為public,其實應該寫一個擷取成員變數的函數的24     int *num;25 };26 27 int main(){28     // 在堆裡產生一個對象29     Tree *tree1 = new Tree();30     tree1->printNum();31 32     // 拷貝建構函式起作用了33     Tree tree2(*tree1);34     tree2.printNum();35     36     // 銷毀tree1對象37     delete tree1;38     // 此時,num是懸null 指標了39     tree2.printNum();40 41     system("pause");42     return 0;43 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.