4.2.5 深拷贝和浅拷贝

浅拷贝:简单的复制拷贝操作

深拷贝:在堆区重新申请空间,进行复制操作

//4.2.5  深拷贝和浅拷贝
#include<iostream>
using namespace std;

class Person
{
public:
    Person()
    {
        cout << "Person的默认构造函数调用" << endl;
    }

    Person(int age,int height)
    {
        m_Height = new int(height);
        cout << "Person的有参函数调用" << endl;
        m_Age = age;
    }

    /*Person(const Person &p)
    {
        cout << "Person的拷贝构造函数调用" << endl;
        m_Age = p.m_Age;
    }*/

    //自己实现拷贝构造函数 解决浅拷贝带来的问题
    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()
    {
        //析构代码,将堆区开辟数据做释放操作
        if (m_Height!=NULL)
        {
            delete m_Height;
            m_Height = NULL;
        }
    
        cout << "Person的析构函数调用" << endl;
    }

    int m_Age;
    int *m_Height;
};
void test01()
{
    Person p1(18,160);
    cout << "p1的年龄为:" << p1.m_Age <<"身高为:"<<*p1.m_Height<< endl;
    Person p2(p1);
    cout << "p2的年龄为:" << p2.m_Age <<"身高为:"<<*p2.m_Height << endl;
}


int main()
{
    test01();
    //test02();
    system("pause");
    return 0;
}

 浅拷贝的问题要在利用深拷贝进行解决

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值