简体   繁体   English

继承C ++(钻石恐惧症)

[英]Inheritance C++ (Diamond dread)

I have the following problem with inheritance (I would love to google it, but don't know the correct keywords it seems). 我在继承方面遇到以下问题(我想在Google上进行搜索,但似乎不知道正确的关键字)。

I have a Module class that implements IModule interface with function A() . 我有一个Module类,该类通过函数A()实现IModule接口。 I also have ClientModule class that inherits Module class and implements IClientModule interface with function B() that inherits IModule interface. 我也有ClientModule类,该类继承了Module类,并使用继承了IModule接口的函数B()实现了IClientModule接口。 This is where I am starting to get ambiguity and double inheritance problems . 这就是我开始感到模棱两可和双重继承问题的地方

Here is the class diagram that should tell a bit more about the problem: 这是应该更详细地说明问题的类图:

在此处输入图片说明

I need to have separated access to Module class with IModule interface and ClientModule with IClientModule interface that offers access to IModule interface as well. 我需要有分离访问ModuleIModule接口和ClientModuleIClientModule接口,提供访问IModule接口为好。

You are running into the "diamond inheritance" problem. 您遇到了“钻石继承”问题。 Diamond inheritance has been discussed many times at this site and elsewhere. 在此站点和其他地方已经多次讨论了钻石继承。 Make the inheritance of class Module and class IClientModule from class IModule virtual. 使从class IModule继承class Moduleclass IClientModule的继承。 This is not a perfect solution; 这不是一个完美的解决方案。 sometimes the magic works, sometimes it doesn't. 有时魔术有效,有时却无效。 Where it doesn't work it's usually a case of demanding too much from inheritance. 在不起作用的地方,通常是对继承的要求过高的情况。

Make IClientModule not inherit IModule (and probably rename it IClient). 使IClientModule不继承IModule(并可能将其重命名为IClient)。 In ClientModule, just inherit from Module and implement IClient. 在ClientModule中,仅继承自Module并实现IClient。

Or, an alternative solution written after reading your comments: 或者,阅读您的评论后编写的替代解决方案:

Make your ClientModule class inherit from IClientModule as in your example. 如示例所示,使ClientModule类继承自IClientModule。 However, instead of inheriting from Module, simply give ClientModule a member variable that is a Module, and forward the calls to this member where needed. 但是,不要从Module继承,只需给ClientModule一个成员变量即Module,然后在需要时将调用转发给该成员。 Something like this: 像这样:

class IModule { virtual void A() {} };
class Module : public IModule { ... };
class IClientModule : public IModule { virtual void B() {} };

class ClientModule : public IClientModule 
{
    // ...
    virtual void A() { _module.A(); }

private:
    Module _module;
};

However, it is likely still better to avoid mashing these together and use my original solution. 但是,最好避免将它们混在一起并使用我的原始解决方案。

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

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