C++编译器至少给一个类添加四个函数
1.默认构造函数(无参,函数体为空)
2.默认析构函数(无参,函数体为空)
3.默认拷贝构造函数,对属性进行值拷贝
4.赋值运算符operator=,对属性进行拷贝
如果类中有属性指向堆区,做赋值操作时也会出现深浅拷贝的问题
#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)
{
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);
p3 = p2 = p1;//连续赋值操作
cout << *p1.m_Age << endl;
cout << *p2.m_Age << endl;
cout << *p3.m_Age << endl;
}
int main()
{
test01();
return 0;
}