1. 程式人生 > 其它 >c++淺拷貝和深拷貝學習案例

c++淺拷貝和深拷貝學習案例

#include <iostream>
using namespace std;

// 淺拷貝:簡單的賦值拷貝操作(編譯器給我們提供的拷貝建構函式就是淺拷貝)
//        存在堆區記憶體重複釋放的問題,因此涉及到堆區記憶體的時候要用深拷貝
//
// 深拷貝:在堆區重新申請空間,進行拷貝操作

class Person{
public:
    Person(){
        cout<<"Person的預設建構函式呼叫"<<endl;
    }

    Person(int age, int height){
        cout<<"Person的有參建構函式呼叫"<<endl;
        m_Age = age;
        m_Height = new int(height); // 在堆區建立
    }

    // 自己實現深拷貝來解決淺拷貝的問題
    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(){
        cout<<"Person的解構函式呼叫"<<endl;
        // 由於在堆區建立的物件需要由程式設計師手動來釋放
        // 所以要在解構函式中實現堆區的記憶體釋放操作
        if(m_Height != NULL){
            delete m_Height;
            m_Height = NULL;
        }
    }
    int m_Age;
    int *m_Height;  // 用指標來指示,因為我們要把這個屬性開闢到堆區
};

void test01(){
    Person p1(18,160);
    cout<<"p1的年齡為:"<< p1.m_Age << ", p1的身高為:" << *p1.m_Height << endl;

    Person p2(p1);
    cout<<"p2的年齡為:"<< p2.m_Age << ", p2的身高為:" << *p2.m_Height << endl;
}


int main(){
    test01();
}

輸出結果為: