# 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;
}
cout << "调用了析构函数" << endl;
}
//重载赋值运算符
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;
//应该先判断是否有属性在堆区,如果有先释放干净,然后再深拷贝
}
//无法进行链式操作
//堆区内存重复释放
//解决方案
//利用深拷贝解决浅拷贝
//引出重载赋值运算符
//进行深浅拷贝
int* m_age;
};
void test01()
{
person p1(18);
person p2(20);
person p3(30);
p2 = p1=p3;
//p2也是指向的堆区内存
//把p1所有的数据给p2
//两块指针指向同一个区域
cout << *p1.m_age << endl;
cout << *p2.m_age << endl;
cout << *p3.m_age << endl;
}
int main(void)
{
test01();
system("pause");
return 0;
}
黑马重载赋值运算符
最新推荐文章于 2024-09-02 20:21:30 发布