c++编译器至少给一个类添加4个函数
- 默认构造(无参)
- 默认析构(无参)
- 默认拷贝(对属性值进行拷贝)
- 赋值运算符 operator 对属性进行值拷贝
如果类中有属性指向堆区,做赋值操作也会出现深浅拷贝问题
先清理置空,再赋值
#include<iostream>
using namespace std;
class Person {
public:
//friend ostream & operator<<(ostream &cout, Person p);
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(30);
//p1 = p2;//赋值操作
p1 = p2 = 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;
}