u 在编写派生类的赋值函数时,注意不要忘记对基类的数据成员重新赋值。例如:
class Base
{
public:
…
Base & operate =(const Base &other); // 类Base 的赋值函数
private:
int m_i, m_j, m_k;
};
class Derived : public Base
{
public:
Derived & operate =(const Derived &other); // 类Derived 的赋值函数
private:
int m_x, m_y, m_z;
};
Derived & Derived::operate =(const Derived &other)
{
//(1)检查自赋值
if(this == &other)
return *this;
//(2)对基类的数据成员重新赋值
Base::operate =(other); // 因为不能直接操作私有数据成员
//(3)对派生类的数据成员赋值
m_x = other.m_x;
m_y = other.m_y;
m_z = other.m_z;
//(4)返回本对象的引用
return *this;
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。