#include<iostream>
using namespace std;
#include <string.h>
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(20);
p3 = p2 = p1;
cout << *p1.m_age << endl;
cout << *p2.m_age << endl;
cout << *p3.m_age << endl;
}
int main() {
test01();
system("pause");
return 0;
}
【C++】赋值运算符重载(堆区开辟内存,深拷贝)
最新推荐文章于 2025-03-21 10:00:00 发布