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;
}
输出结果:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)