是必要的纯抽象类(接口)的虚拟继承

时间:2011-06-19 17:08:30

标签: c++ inheritance multiple-inheritance virtual-inheritance

为什么在编译器下面的代码中抱怨PureAbstractBaseMultiplyInheritedClass的模糊基类?我发现我PureAbstractBase中有MultiplyInheritedClass的两份副本,而FirstConreteClassSecondConreteClass应该是虚拟派生的,因为它们是钻石的中间行(并且确实解决了以下代码的问题)。但即使我有两个接口副本,为什么MultiplyInheritedClass中的代码不仅仅覆盖两者并且明确地选择MultiplyInheritedClass中定义的接口类?

#include <iostream>
using namespace std;

class PureAbstractBase {
  public:
    virtual void interface() = 0;
};

// I know that changing the following line to:
// class FirstConcreteClass : public virtual PureAbstractBase {
// fixes the problem with this hierarchy
class FirstConcreteClass : public PureAbstractBase {
  public:
    virtual void interface() { implementation(); }
  private:
    void implementation() { cout << "This is object FirstConcreteClass\n"; }
};

// I know that changing the following line to:
// class SecondConcreteClass : public virtual PureAbstractBase {
// fixes the problem with this hierarchy
class SecondConcreteClass : public PureAbstractBase {
  public:
    virtual void interface() { implementation(); }
  private:
    void implementation() { cout << "This is object SecondConcreteClass\n"; }
};

class MultiplyInheritedClass : public FirstConcreteClass,
                               public SecondConcreteClass {
  public:
    virtual void interface() { implementation(); }
  private:
    void implementation() { cout << "This is object MultiplyInheritedClass\n"; }
};

此外,为什么我没有以下层次结构的问题?在这种情况下,ConcreteHandler类是否有三个AbstractTaggingInterface副本?那么为什么它与上面的例子没有相同的问题呢?

#include <iostream>
using namespace std;

class AbstractTaggingInterface {
  public:
    virtual void taggingInterface() = 0;
};

class FirstAbstractHandler : public AbstractTaggingInterface {
  public:
    virtual void taggingInterface() { cout << "FirstAbstractHandler\n"; }
    virtual void handleFirst() = 0;
};

class SecondAbstractHandler : public AbstractTaggingInterface {
  public:
    virtual void taggingInterface() { cout << "SecondAbstractHandler\n"; }
    virtual void handleSecond() = 0;
};

class ThirdAbstractHandler : public AbstractTaggingInterface {
  public:
    virtual void taggingInterface() { cout << "ThridAbstractHandler\n"; }
    virtual void handleThird() = 0;
};

class ConcreteHandler : public FirstAbstractHandler,
                        public SecondAbstractHandler,
                        public ThirdAbstractHandler {
  public:
    virtual void taggingInterface() = { cout << "ConcreteHandler\n"; }
    virtual void handleFirst() {}
    virtual void handleSecond() {}
    virtual void handleThird() {}
};

我试图围绕这一切,因为我最近与一位同事进行了一次对话,他声称如果你是从没有任何数据成员的纯虚拟类(接口)继承,那么就不需要虚拟继承。我认为理解为什么前一个代码示例不起作用而后者确实会在很长的路要走这一点(并清楚他的评论究竟是什么意思)。提前致谢。

4 个答案:

答案 0 :(得分:5)

你需要虚拟继承来克服钻石歧义:

class FirstConcreteClass  : public virtual PureAbstractBase { ... };
class SecondConcreteClass : public virtual PureAbstractBase { ... };

冗长的解释:假设你有这个:

// *** Example with errrors! *** //
struct A { virtual int foo(); };
struct B1 : public A { virtual int foo(); };
struct B2 : public A { virtual int foo(); };
struct C: public B1, public B2 { /* ... */ };  // ambiguous base class A!

int main() {
  A * px = new C;                              // error, ambiguous base!
  px->foo();                                   // error, ambiguous override!
}

虚函数foo的继承是不明确的,因为它有三种方式:来自B1,来自B2和来自A。继承图形成一个“钻石”:

   /-> B1 >-\
A->          ->C
   \-> B2 >-/

通过使继承虚拟,struct B1 : public virtual A;等,允许C*的任何基类调用正确的成员:

struct A { virtual int foo(); };
struct B1 : public virtual A { virtual int foo(); };
struct B2 : public virtual A { virtual int foo(); };
struct C: public B1, public B2 { virtual int foo(); };

我们必须也定义C::foo()才有意义,否则C将没有明确定义的成员foo

更多细节:假设我们现在有一个正确的虚拟继承类C,如上所述。我们可以根据需要访问所有各种虚拟成员:

int main() {
  A * pa = new C;
  pa->foo();      // the most derived one
  pa->A::foo();   // the original A's foo

  B1 * pb1 = new C;
  pb1->foo();     // the most derived one
  pb1->A::foo();  // A's foo
  pb1->B1::foo(); // B1's foo

  C * pc = new C;
  pc->foo();      // the most derived one
  pc->A::foo();   // A's foo
  pc->B1::foo();  // B1's foo
  pc->B2::foo();  // B2's foo
  pc->C::foo();   // C's foo, same as "pc->foo()"
}

更新:正如David在评论中所说,重要的一点是中间类B1B2实际上是继承的,以便进一步的类(在这种情况下{ {1}})可以继承他们,同时保持C的继承明确无误。抱歉最初的错误,谢谢你的纠正!

答案 1 :(得分:5)

您的第一个示例失败,因为编译器无法消除implementation()的三个实现之间的歧义。您正在覆盖MultiplyInheritedClass中的该方法,该方法实际上会覆盖FirstConcreteClass::implementationSecondConcreteClass::implementation(一旦虚拟,始终为虚拟)。但是,MultiplyInheritedClass的接口中仍存在两个虚拟呼叫,这使呼叫在呼叫站点处不明确。

您的示例在没有virtual继承的情况下工作的原因是公共基类没有冲突的实现。换句话说:

class Base
{
public:
    void DoSomething() {
    std::cout << "TADA!";
    }
}

class One : public Base
{
    //...
}

class Two : public Base
{
    //...
}

class Mixed : public One, public Two
{
    //...
}

int main()
{
    Mixed abc;
    abc.DoSomething(); //Fails because the compiler doesn't know whether to call
                       // One::DoSomething or Two::DoSomething, because they both
                       // have implementations.

    //In response to comment:
    abc.One::DoSomething(); //Succeeds! You removed the ambiguity.
}

因为您的示例具有所有纯虚函数,所以编译器不需要消除歧义的多个实现。因此,只存在一个实现,并且调用是明确的。

答案 2 :(得分:1)

我尝试了两个问题代码,并且它们在实例化多继承类的对象时工作正常。它不仅适用于多态,例如:

PureAbstractBase* F;
F = new MultiplyInheritedClass();

原因很清楚:它不知道应该链接哪个抽象基类副本(对不好的表达方式,我理解这个想法但不能表达它)。并且由于简单地使得派生类中只存在一个副本,所以它很好。

Billy ONeal的代码也不清楚,我们应该放置什么而不是评论?

如果我们放置:

public:    
void DoSomething() 
{    std::cout << "TADA!";    }

它工作正常,因为没有虚拟性。

我在Visual Studio 2008上工作。

答案 3 :(得分:0)

为什么不这样做(在Benjamin Supnik's blog entry中建议):

#include <iostream>

class PureAbstractBase {
public:
    virtual void interface() = 0;
};

class FirstConcreteClass : public PureAbstractBase {
public:
    virtual void interface() { implementation(); }
private:
    void implementation() { std::cout << "Fisrt" << std::endl; }
};

class SecondConcreteClass : public PureAbstractBase {
public:
    virtual void interface() { implementation(); }
private:
    void implementation() { std::cout << "Second" << std::endl; }
};

class MultiplyInheritedClass : public FirstConcreteClass,
                               public SecondConcreteClass 
{
public:
    virtual void interface() { implementation(); }
private:
    void implementation() { std::cout << "Multiple" << std::endl; }
};

int main() {
MultiplyInheritedClass mic;
mic.interface();

FirstConcreteClass *fc = &mic; //disambiguate to FirstConcreteClass 
PureAbstractBase *pab1 = fc;
pab1->interface();

SecondConcreteClass *sc = &mic; //disambiguate to SecondConcreteClass 
PureAbstractBase *pab2 = sc;
pab2->interface();
}

给出:

Multiple
Multiple
Multiple    

这样:

  • 没有涉及虚拟基地(你真的需要它们吗?)
  • 您可以通过MultiplyInheritedClass
  • 的实例调用overriden函数
  • 歧义被两阶段转换删除
相关问题