当班级是孩子时重载赋值运算符

Sir*_*lot 6 c++ assignment-operator

如何使用赋值运算符实现设置基类成员?例如,如果有人在派生类中定义赋值运算符,如下所示:

(其中两个colourColour()是基类的成员-意味着线如下所示被非法)

Derived& Derived::operator=(const Derived& rhs) 
{
if (&rhs != this)
{

    Colour(rhs.colour);    // not allowed
        Colour(rhs.Colour());  // not allowed
}
return *this;
}
Run Code Online (Sandbox Code Playgroud)

解决办法是什么?有没有办法在基地链接运算符重载?我做的事情......

Derived& Derived::operator=(const Derived& rhs) : Base::operator=(rhs)
...?
Run Code Online (Sandbox Code Playgroud)

BЈо*_*вић 6

它是这样完成的:

class B
{
 public:
  B& operator=( const B & other )
  {
    v = other.v;
    return *this;
  }
  int v;
};

class D : public B
{
 public:
  D& operator=( const D & other )
  {
    B::operator=( other );
    return *this;
  }
};
Run Code Online (Sandbox Code Playgroud)


edu*_*ffy 4

你已经很接近了,只需将该调用放入方法主体中即可。

 if (&rhs != this)
 {
    Base::operator=(rhs);
    // ...
Run Code Online (Sandbox Code Playgroud)