【问题标题】:Operator = overloading in virtual inheritance in c++运算符= C++中虚拟继承中的重载
【发布时间】:2015-08-08 15:14:02
【问题描述】:

假设我们有一个像下面这样的层次结构。我们是否必须调用虚拟基类 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;
    }
 }

【问题讨论】:

  • 取决于B/C::operator 的实现。他们可能确实打电话给A::operator =
  • D只有两个父类(B和C)不要在复制操作符中调用A(但是,在构造过程中,最派生类必须调用虚基构造函数)

标签: c++ oop operator-overloading base-class virtual-inheritance


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-12
    • 2011-12-05
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多