16.对象的深浅拷贝问题

程序1:

//2022年9月15日08:39:35
#include <iostream>
using namespace std;

class Maker
{
public:
    int mId;
    int mAge;
public:
    Maker(int id, int age)
    {
        mId = id;
        mAge = age;
    }
};

void test01()
{
    Maker m1(1, 18);
    Maker m2(m1);

    cout << "m1.id = " << m1.mId << ", m1.age = " << m1.mAge << endl;
    cout << "m2.id = " << m2.mId << ", m2.age = " << m2.mAge << endl;

    /*
    m2.mId = m1.mId;
    m2.mAge = m1.mAge;
    */
}

int main()
{
    test01();
    system("pause");
    return EXIT_SUCCESS;
}

输出结果:



程序2:

//2022年9月15日08:39:35
#include <iostream>
using namespace std;

class Student
{
public:
    char *pName;
    int age;
public:
    Student(const char *name, int Age)
    {
        pName = (char *)malloc(strlen(name) + 1);
        strcpy(pName, name);
        age = Age;
    }

    ~Student()
    {
        cout << "析构函数" << endl;
        if (pName != NULL)
        {
            free(pName);
            pName = NULL;
        }
    }
};

void test02()
{
    Student s1("小花", 18);
    Student s2(s1);

    cout << "s1 Name = " << s1.pName << ", s1 age = " << s1.age << endl;
    cout << "s2 Name = " << s2.pName << ", s2 age = " << s2.age << endl;
}

int main()
{
    test02();
    system("pause");
    return EXIT_SUCCESS;
}

异常:

分析:



程序3:

//2022年9月15日08:39:35
#include <iostream>
using namespace std;

class Student
{
public:
    char *pName;
    int age;
public:
    Student(const char *name, int Age)
    {
        pName = (char *)malloc(strlen(name) + 1);
        strcpy(pName, name);
        age = Age;
    }
    //深拷贝
    Student(const Student &stu)
    {
        cout << "自己的拷贝构造函数" << endl;
        //1.申请空间
        pName = (char *)malloc(strlen(stu.pName) + 1);
        //2.拷贝数据
        strcpy(pName, stu.pName);
        age = stu.age;
    }

    ~Student()
    {
        cout << "析构函数" << endl;
        if (pName != NULL)
        {
            free(pName);
            pName = NULL;
        }
    }
};

void test02()
{
    Student s1("小花", 18);
    Student s2(s1);

    cout << "s1 Name = " << s1.pName << ", s1 age = " << s1.age << endl;
    cout << "s2 Name = " << s2.pName << ", s2 age = " << s2.age << endl;
}

int main()
{
    test02();
    system("pause");
    return EXIT_SUCCESS;
}

输出结果:

posted @   CodeMagicianT  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示