赋值运算符重载:
c++编译器至少给一个类添加4个函数:
- 默认构造函数(无参,函数体为空)
- 默认析构函数(无参,函数体为空)
- 默认拷贝构造函数,对属性进行值拷贝
- 赋值运算符 operator=, 对属性进行值拷贝
问题描述
如果类中有属性指向 **堆区**,做 = 赋值操作时也会出现**深浅拷贝**问题:
例如:
class Person
{
public:
Person(int age)
{
//将年龄数据开辟到 堆区
m_Age = new int(age);
}
//年龄的指针
int *m_Age;
};
解决方案:
使用赋值运算符解决深浅拷贝问题:
通用的写法:operator=
直接看代码和相应的注释:
class Person
{
public:
Person(int age)
{
//将年龄数据开辟到 堆区
m_Age = new int(age);
}
//重载赋值运算符
Person& operator=(Person &p)
//这里不可以返回void,因为还是为了链式编程,实现a=b=c的效果(内置的=就可以实现这个功能)
{
//先判断待赋值对象是否有属性在堆区,如果有先释放干净,然后再深拷贝
if (m_Age != NULL)
{
delete m_Age;
m_Age = NULL;
}
//编译器提供的代码是浅拷贝
//m_Age = p.m_Age;
//提供深拷贝 解决浅拷贝的问题
m_Age = new int(*p.m_Age);
//返回自身
return *this;
}
~Person()
{
if (m_Age != NULL)
{
delete m_Age;
m_Age = NULL;
}
}
//年龄的指针
int *m_Age;
};
void test01()
{
Person p1(18);
Person p2(20);
Person p3(30);
p3 = p2 = p1; //赋值操作
cout << "p1的年龄为:" << *p1.m_Age << endl;
cout << "p2的年龄为:" << *p2.m_Age << endl;
cout << "p3的年龄为:" << *p3.m_Age << endl;
}
int main() {
test01();
return 0;
}
总结一下:拷贝构造函数和赋值运算符重载都能解决深浅拷贝问题,一个是调用 拷贝构造函数
拷贝,一个是使用 =
运算符进行拷贝。
重写拷贝构造函数解决深浅拷贝问题