c++编译器至少给一个类添加4个函数:
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)
{
//编译器是提供浅拷贝
//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 test()
{
Person p1(18);
Person p2(20);
Person p3(20);
p3 = p2 = p1;//完成这步 需要返回自身
//p2 = p1;//赋值操作 p1 = p2 =18;
cout << "p1的年龄为: " << *p1.m_Age << endl;
cout << "p2的年龄为: " << *p2.m_Age << endl;
cout << "p3的年龄为: " << *p3.m_Age << endl;
}
int main()
{
test();
/*int a = 10;
int b = 10;
int c = 10;
c = b = a;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;*/
return 0;
}