C++中类似接口的继承

Joh*_*nes 6 c++ inheritance gcc abstract-class g++

我有以下情况,图中是我班级的理论继承图:

继承图

这个想法基本上是为了

1)有两个可以在不同平台上实现的抽象基类(在我的例子中是两个不同的操作系统)

2)允许BBase向上转换为ABase,以便能够同时处理两者(例如,将两种类型的实例保存在一个列表中).

3)在ABase和BBase中实现某些常用功能.

现在,用C++表示这个的最佳方法是什么?虽然它确实支持多重继承,但我不知道这样的多级继承.问题是B继承自A和BBase,后者又从ABase继承.只需在C++中翻译这个1:1(以下代码),C++编译器(GNU)就会抱怨AB实现没有实现ABase :: foo().

class ABase
{
public:
    virtual void foo() = 0;
    void someImplementedMethod() {}
};

class BBase : public ABase
{
public:
    virtual void bar() = 0;
    void someOtherImplementedMethod() {}
};

class A : public ABase
{
public:
    A() {}
    void foo() {}
};

class B : public A, public BBase
{
public:
    B() : A() {}
    void bar() {}
};

int main()
{
    B b;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

您如何更改此继承模型以使其与C++兼容?

编辑:图中倒置的箭头并将"向下浇筑"修正为"向上浇筑".

Gri*_*zly 7

您可以使用虚拟继承在C++中直接使用该类型的层次结构:

class ABase{...};
class BBase : public virtual ABase {...};
class A     : public virtual ABase {...};
class B     : public A, public BBase {...};
Run Code Online (Sandbox Code Playgroud)

当然,如果您计划拥有更多级别,那么对B使用虚拟继承也是一个好主意,所以你会得到

class B     : public virtual A, public virtual BBase {...};
Run Code Online (Sandbox Code Playgroud)