10.深拷贝与浅拷贝

2021-02-02  本文已影响0人  lxr_
#include<iostream>
using namespace std;

//浅拷贝:简单的赋值拷贝操作(*******可能会带来堆区内存的重复释放******)
//深拷贝:在堆区重新申请空间,进行拷贝操作(深拷贝解决浅拷贝带来的问题)
//***如果属性有在堆区开辟内存,一定要自己提供拷贝构造函数,防止浅拷贝带来的问题,如果有数组,需要将数据全部拷贝***
class People
{
public:
    int m_Age;
    int* m_Height;

    People()
    {
        cout << "People默认构造" << endl;
    }
    People(int age,int height)
    {
        m_Age = age;
        m_Height = new int(height);//手动开辟在堆区
        cout << "People有参构造" << endl;
    }
    People(const People& p)
    {
        m_Age = p.m_Age;
        //m_Height = p.m_Height;****浅拷贝带来重复释放内存的问题,增加了一个指针指向已存在的内存地址
        m_Height = new int(*p.m_Height);//深拷贝增加了一个指针并申请了一个新的内存,是这个增加的指针指向新的内存
        cout << "People拷贝构造" << endl;
    }
    ~People()
    {
        //析构函数将堆区开辟的内存释放
        if (m_Height != NULL)
        {
            cout << (int)m_Height << endl;
            delete m_Height;
            m_Height = NULL;
        }
        cout << "People析构" << endl;
    }
};
void test07()
{
    People p1(18,160);
    cout << "p1的年龄:" << p1.m_Age << endl;
    cout << "p1的身高:" << *p1.m_Height << endl;
    
    People p2(p1);
    cout << "p2的年龄:" << p2.m_Age << endl;
    cout << "p2的身高:" << *p2.m_Height<< endl;
}
int main()
{
    test07();
    system("pause");
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读