11.2.5重学C++之【深拷贝与浅拷贝】

#include<stdlib.h>
#include<iostream>
#include<string>
using namespace std;


/*
    4.2 对象的初始化和清理
    4.2.5 深拷贝与浅拷贝
        面试经典问题,有坑
        浅拷贝:简单的赋值拷贝操作
        深拷贝:在堆区重新申请空间,进行拷贝操作
    总结:若属性有在堆区开辟的,一定要自己提供拷贝构造函数(手动深拷贝),防止默认浅拷贝带来问题
*/


class Person{
public:
    Person(){
        cout << "Person 默认无参构造" << endl;
    }

    Person(int _age, int _height){
        cout << "Person 有参构造" << endl;
        age = _age;
        height = new int(_height); // 指针给指针赋值
        // 利用new在堆区创建数据时,会返回该数据对应的指针
        // new出来的堆区数据,手动释放用delete
        // 堆区(由程序员分配和释放,若程序员未释放则程序结束时由OS回收),在堆区手动创建的数据应手动释放
        // 堆区:程序员利用new在堆区开辟内存空间
    }

    Person(const Person & p){
        cout << "拷贝构造" << endl;
        age = p.age;
        //height = p.height; // 编译器默认利用浅拷贝实现,这样有问题(指针=具体数值,错误)
        //深拷贝操作解决上行问题--需手动实现
        height = new int(*p.height); // 先取址得到具体数值再利用new转为指针,再给指针赋值
    }

    ~Person(){
        cout << "Person 析构" << endl;
        if(height != NULL){
            delete height; // 析构作用:将堆区开辟的数据做手动释放操作
            height = NULL;
        }
    }

    int age;
    int * height; // 自定义指针类型成员属性
};


void test1(){
    Person p1(18, 160);
    cout << "p1年龄:" << p1.age << endl;
    cout << "p1身高:" << *p1.height << endl; // 用取址符*访问指针(存地址)指向的内存(存具体值)

    Person p2(p1);
    cout << "p2年龄:" << p2.age << endl;
    cout << "p2身高:" << *p2.height << endl;
}


int main(){
    test1();

    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/HAIFEI666/article/details/114842250