c++中虚继承中的Operator =重载

Operator = overloading in virtual inheritance in c++

本文关键字:重载 Operator 继承 c++      更新时间:2023-10-16

假设我们有一个如下所示的层次结构。是否必须调用虚基类A的operator =方法?

class A
{ ... }
class B : virtual public A
{ ... }
class C : virtual public A
{ ... }
class D : public B, public C
{
   D& operator = (const D& other)
   {
      if(this != &other)
      {
       // A::operator = (other); is this line correct???
          B::operator = (other);
          C::operator = (other);
          ....
       }
      return *this;
    }
 }

就像@ emadpress在评论中所说的,这取决于operator=在层次结构中的处理方式。如果B和C使用A对operator=的实现,那么你不必在D的实现中显式地使用它。

请记住,为了保持语义的直接性,您可能应该使用A在B和c中的实现。当重载是引入大量复杂性的好方法时,尝试沿着层次结构树一路向上。