通过从具体类派生来填写抽象类成员

时间:2015-06-02 14:31:26

标签: c++ inheritance multiple-inheritance class-design

假设我有一个继承自另一个接口(纯抽象类)的接口

class BaseInterface
{};

然后另一个接口构建在BaseInterface

之上
class ExtendedInterface : public BaseInterface
{};

现在,我有一个实现BaseInterface的具体类:

class Base : public BaseInterface
{};

现在,我想实现ExtendedInterface,但由于我已经有了Base,我想用base填充BaseInterface成员。 E.g:

class Extended : public ExtendedInterface, public Base
{};

这似乎不起作用。我得到的投诉是我无法实例化扩展,因为它是一个抽象类。我能让它工作的唯一方法是使用虚拟继承,但后来我得到关于继承优势的编译器警告。

1 个答案:

答案 0 :(得分:3)

问题是什么?

通过多重继承,Extended会从BaseInterface继承两次。这意味着有两个独立的BaseInterface子对象:

  • 一个是通过具体的Base类继承的,它覆盖了所有纯虚函数。

  • 但是另一个是通过ExtendedInterface类继承的,它仍然是抽象的。

enter image description here

因此,由于Extended的某些子对象仍具有纯虚函数,因此您的类仍然是一个无法实例化的抽象类。

如何解决?

尽管您显然希望只有一个BaseInterface的多重继承,但您需要使用虚拟继承:

class BaseInterface                                       
{ virtual void test()=0; };                              // abstract class

class ExtendedInterface : public virtual BaseInterface   // virtual inheritance
{};                                                      // abstract class

class Base : public virtual BaseInterface                // virtual inheritance
{ void test() override {} };                             // concrete class

class Extended : public ExtendedInterface, public Base   // multiple 
{};                             // thanks to virtual inheritance, concerete class 

使用此逻辑,BaseInterface中只有一个Extended,虚拟函数被覆盖,您可以实例化它。

这是online demo