【问题标题】:Filling out abstract class members by deriving from concrete class通过从具体类派生来填充抽象类成员
【发布时间】:2015-06-02 14:31:26
【问题描述】:

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

class BaseInterface
{};

然后在 BaseInterface 上构建另一个接口

class ExtendedInterface : public BaseInterface
{};

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

class Base : public BaseInterface
{};

现在,我想实现 ExtendedInterface,但由于我已经有了 Base,我想用 base 填写 BaseInterface 成员。例如:

class Extended : public ExtendedInterface, public Base
{};

这似乎不起作用。我抱怨我无法实例化扩展,因为它是一个抽象类。我可以让它工作的唯一方法是使用虚拟继承,但随后我收到关于通过支配继承的编译器警告。

【问题讨论】:

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


    【解决方案1】:

    有什么问题?

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

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

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

    因此,由于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 
    

    按照这个逻辑,Extended中只有一个BaseInterface,虚函数被覆盖,你可以实例化它。

    这里是online demo

    【讨论】:

      猜你喜欢
      • 2012-09-25
      • 2017-06-19
      • 1970-01-01
      • 2011-01-08
      • 2011-02-01
      • 1970-01-01
      • 2018-09-12
      • 1970-01-01
      • 2021-12-05
      相关资源
      最近更新 更多