* 深浅拷贝问题
#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)
{
//编译器是提供浅拷贝
//m_age = p.m_age;
//应该先判断是否有属性在堆区,如果有 先释放干净,然后再深拷贝
if (m_age != NULL)
{
delete m_age;
m_age = NULL;
}
//深拷贝
m_age = new int(*p.m_age);
//返回自身
return *this;//指向自身的指针:this指针,通过*解引用找回自身
}
int* m_age;
};
void test01()
{
Person p1(18);
Person p2(20);
Person p3(23);
p2 = p1 = p3;
cout << "p1的年龄为:" << *p1.m_age << endl;
cout << "p2的年龄为:" << *p2.m_age << endl;
cout << "p3的年龄为:" << *p3.m_age << endl;
}
int main()
{
test01();
system("pause");
return 0;
}