简体   繁体   English

C ++中类似接口的继承

[英]Interface-like inheritance in C++

I have the following situation, pictured is the theoretical inheritance graph of my classes: 我有以下情况,图中是我班级的理论继承图:

继承图

The idea is basically to 这个想法基本上是为了

1) have two abstract base classes that can be implemented on different platforms (in my case two different operating systems) 1)有两个可以在不同平台上实现的抽象基类(在我的例子中是两个不同的操作系统)

2) allow BBase to be up-castable to ABase to be able to handle both equally at times (eg to hold instances of both types in one list). 2)允许BBase向上转换为ABase,以便能够同时处理两者(例如,将两种类型的实例保存在一个列表中)。

3) implement certain common functionality in ABase and BBase. 3)在ABase和BBase中实现某些常用功能。

Now, what would be the best way to represent this in C++? 现在,用C ++表示这个的最佳方法是什么? Even though it does support multiple inheritance, multi-level inheritence like this is not possible to my knowledge. 虽然它确实支持多重继承,但我不知道这样的多级继承。 The problem is that B inherits from A and BBase, which both in turn inherit from ABase. 问题是B继承自A和BBase,后者又从ABase继承。 Simply translating this 1:1 (following code) in C++, a C++ compiler (GNU) will complain that ABase::foo() is not implemented in B. 只需在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;
}

How would you change this inheritance model to make it compatible to C++? 您如何更改此继承模型以使其与C ++兼容?

EDIT: Inverted arrows in diagram and corrected "down-castable" to "up-castable". 编辑:图中倒置的箭头并将“向下浇筑”修正为“向上浇筑”。

You can directly use that type of hierarchy in C++ by using virtual inheritance : 您可以使用虚拟继承在C ++中直接使用该类型的层次结构:

class ABase{...};
class BBase : public virtual ABase {...};
class A     : public virtual ABase {...};
class B     : public A, public BBase {...};

Of course if you plan on having more levels, it might be a good idea to use virtual inheritance for B too, so you would get 当然,如果您计划拥有更多级别,那么对B使用虚拟继承也是一个好主意,所以你会得到

class B     : public virtual A, public virtual BBase {...};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM