//赋值运算符重载
#include <iostream>
using namespace std;
class Person
{
public:
Person(int age)//有参构造函数
{
m_Age=new int(age);//在堆区开辟一个空间(会返回int* 类型)
}
~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;//int类型的指针
};
void test01()
{
Person p1(18);
Person p2(20);
Person p3(30);
p3 = p2 = p1;//连等操作
cout << *p1.m_Age << endl;
cout << *p2.m_Age << endl;
cout << *p3.m_Age << endl;
}
int main()
{
test01();//30
return 0;
}
赋值运算符重载
本文详细介绍了如何在C++中重载赋值运算符,包括使用有参构造函数、析构函数确保内存管理以及深拷贝技术,通过`test01`函数展示了实例应用。
摘要由CSDN通过智能技术生成