赋值运算符的重载主要解决浅拷贝和深拷贝问题
赋值运算符的重载只能在类内实现
class Person
{
public:
Person &operator=(const Person &p)
{
if (m_age != NULL)
{
delete m_age;
m_age = NULL;
}
this->m_age = new int(*p.m_age);
return *this;
}
Person(int age)
{
m_age = new int(age);
}
int *m_age;
~Person()
{
if (m_age != NULL)
{
delete m_age;
m_age = NULL;
}
}
};
void test01()
{
Person p1(20);
Person p2(10);
p2 = p1;
cout << *p2.m_age << endl;
}
int main()
{
test01();
return 0;
}