深拷贝浅拷贝

//1.
//对象拷贝的2种形式:
//(1) 类名 对象2(对象1);	//people per1(per);
//(2) 类名 对象2 = 对象1 ;	//people per1 = per;

//2.
//所以在对“含有指针成员的对象”进行拷贝时,必须要【自己定义拷贝构造函数】,
//使拷贝构造后的对象指针成员有自己的内存空间,即进行【深拷贝】,避免内存泄漏。

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <cstring>
using namespace std;

class people
{
public:
    people(const char* nam, int a)
    {
        this->name = new char[strlen(nam) + 1];
        strcpy(name, nam);
        this->age = a;
    }

#if 0
    // 浅拷贝(就是拷贝构造函数)
    // 实际上,拷贝构造函数由编译系统自动完成,不必用户去显示地调用,也不用显示地定义。
    people(people& peo)
    {
        this->name = peo.name;
        this->age = peo.age;
    }
#endif

#if 1
    // 深拷贝
    people(people& peo)
    {
        this->name = new char[strlen(peo.name) + 1];
        strcpy(this->name, peo.name);
        this->age = peo.age;
    }
#endif

    ~people()
    {
        cout << "~people:" << (int)name << endl;;
        delete[] name;
    }

    void show()
    {
        cout << name << " " << age << endl;
    }

    ///
    /// \brief get_ad
    /// \param p
    /// 打印相关地址
    void get_ad(people& p)
    {
        cout << "对象本身地址:" << (int)&p << endl;
        cout << "&age:" << (int)&p.age << endl;
        cout << "&name:" << (int)p.name << endl;
    }

private:
    char* name;
    int age;
};

int main()
{
    people per("zhang", 19);
    people per1(per);

    cout << "【per】中的地址成员地址:" << endl;
    per.get_ad(per);	cout << endl;

    cout << "【per1】中的地址成员地址:" << endl;
    per1.get_ad(per1);	cout << endl;

    return 0;
}

使用深拷贝:程序运行正常。
在这里插入图片描述
使用浅拷贝,程序运行崩溃。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值