深拷贝与浅拷贝

 

#include<iostream>
using namespace std;
class Person{
    public:
    Person(){
        cout<<"无参构造函数!"<<endl;
    }
    Person(int age,int height){
        m_Age=age;
        m_Height=new int(height);
        cout<<" 带参构造函数!"<<endl;
        cout<<" 年龄 "<<m_Age<<endl;
        cout<<" 身高 "<<*m_Height<<endl;
    }
    
    Person(const Person &p){
        cout<<"拷贝构造函数"<<endl;
        m_Age=p.m_Age;
        //m_Height=p.m_Height; //浅拷贝
        m_Height=new int(*p.m_Height); //深拷贝
        cout<<" 拷贝构造年龄 "<<m_Age<<endl;
        cout<<" 拷贝构造身高 "<<*m_Height<<endl;
    }

    ~Person(){
        if (m_Height!=NULL){
            delete m_Height;
            m_Height=nullptr;
        }
       
        cout<<"析构函数"<<endl;
    }
    int m_Age=0;
    int *m_Height=nullptr;

};

void test01(){
    Person person1(10,110);
    Person person2(person1);
}

int main(int args ,char **argv){
    test01();
    return 0;

}

  

posted @ 2024-03-22 17:08  FigureOut  阅读(8)  评论(0)    收藏  举报