16-【每天亿点点C++,简单又有趣儿】深拷贝浅拷贝

#include<iostream>
#include<string>
using namespace std;
class Pige
{
public:

    Pige()
    {
         cout << "Pige 无参(默认)构造函数" <<endl;
    }
    Pige(int a,int hi)
    {
         age = a;
         h = new int(hi);
         cout << "Pige 有参构造函数" <<endl;
    }
    Pige(const Pige &p)
    {
        //把一个对象复制一份新的
        age = p.age;
        // h = p.h;编译器提供的是浅拷贝
        h = new int(*p.h); //深拷贝
        cout << "Pige 拷贝构造函数" <<*p.h<<endl;
    }
    ~Pige()
    {
        //将堆区数据释放
        if (h != NULL)
        {
            delete h;
            h = NULL;
        }

        cout << "Pig 析构函数" <<endl;
    }
    int age;
    int * h;
};

void test_09()
{
    Pige p1(17,160);
    cout << "p1 age = " << p1.age << "  h = " << *p1.h << "  " << p1.h <<endl;
    Pige p2(p1);//浅拷贝
    cout << "p2 age = " << p2.age << "  h = " << *p2.h << "  " << p2.h <<endl;
}
int main()
{
  test_09();
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/magic_shuang/article/details/107591069
今日推荐