1 Star 0 Fork 0

CoderQi/cpp

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
赋值运算符重载.cpp 783 Bytes
一键复制 编辑 原始数据 按行查看 历史
CoderQi 提交于 2023-04-08 20:07 +08:00 . 运算符重载
#include<iostream>
using namespace std;
class Person
{
public:
Person(int age)
{
m_Age = new int(age);
}
~Person()
{
if (m_Age != NULL)
{
delete m_Age;
m_Age = NULL;
}
}
//赋值运算符重载
Person& operator=(Person& p)
{
if (m_Age != NULL)//应该先判断是否有属性在堆区,如果有,先释放干净,然后深拷贝
{
delete m_Age;
m_Age = NULL;
}
//深拷贝
m_Age = new int(*p.m_Age);
//返回对象本身
return *this;
}
int *m_Age;
};
void test01()
{
Person p1(18);
Person p2(20);
Person p3(25);
p3 = p2 = p1;
cout << "p1的年龄是: " << *p1.m_Age << endl;
cout << "p2的年龄是: " << *p2.m_Age << endl;
cout << "p3的年龄是: " << *p3.m_Age << endl;
}
int main()
{
test01();
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/programmercg/cpp.git
git@gitee.com:programmercg/cpp.git
programmercg
cpp
cpp
master

搜索帮助