继承中的赋值运算符重载
1、为什么要重写赋值运算符重载?
对于堆空间的数据成员,要进行深赋值,如果是默认的浅赋值行为,就会导致自赋值、重析构、内存泄漏
2、解决方法
在子类的赋值函数里面(注意是在里面)初始化父类或者内嵌子对象的赋值函数。
子类:
class B :public A
{
public:
B()
{
cout << "B()" << endl;
}
B(const B& another):A(another),c(another.c)
{
cout << "B(const B& another)" << endl;
}
B& operator=(B& another)
{
if (this == &another)
return *this;
A::operator=(another);//注意父类
c = (another.c);//注意内嵌子对象
cout << "B& operator=(const B& another)" << endl;
return *this;
}
private:
C c;
};