简体   繁体   English

接口的钻石继承(C ++)

[英]Diamond inheritance of interfaces (C++)

I've stumbled upon a diamond inheritance problem, and I am not sure of the best solution. 我偶然发现了钻石继承问题,但我不确定最佳解决方案。 The following code works and has no diamond problem: 以下代码有效,并且没有钻石问题:

class Element { /* pure virtual functions */ };
class Diode : public Element {};
class Thyristor : public Diode {};

I don't like the public inheritance though, because a Thyristor is not a Diode, it just acts like a Diode often enough that I want to use a lot of the Diode code. 但是我不喜欢公共继承,因为晶闸管不是二极管,它经常像二极管一样工作,以至于我想使用很多二极管代码。 I can make it work by using composition rather than inheritance, but that results in duplication of internal data structures between Diode and Thyristor which I don't like. 我可以通过使用合成而不是继承来使其工作,但这导致Diode和晶闸管之间的内部数据结构重复,这是我不喜欢的。 What I would like to do is use private inheritance. 我想做的是使用私有继承。 If I do that, then Thyristor would also need to inherit publicly from Element: 如果我这样做,那么晶闸管也需要从Element公开继承:

class Thyristor : public Element, private Diode {};

The potential problem is that I have now created a diamond, as Element is inherited directly and through Diode. 潜在的问题是我现在创建了一个菱形,因为Element是直接并通过Diode继承的。 Is this a problem if Element is a pure virtual function? 如果Element是纯虚函数,这是一个问题吗? If it is, what is the proper way to solve this problem, making changes only to the Thyristor class? 如果是的话,仅对晶闸管类进行更改的解决该问题的正确方法是什么?

You should surely use aggregation instead of inheritance this case. 在这种情况下,您一定要使用聚合而不是继承。

Just trace back and ask yourself: why I'm inheriting here? 追溯一下,问问自己:为什么我要在这里继承? How the thyristors and diodes could be used in the outer code? 外部代码中如何使用晶闸管和二极管? Quite soon you'll find you don't need inheritance for elements, just aggregate necessary behaviors (number of contacts, conduction behavior, etc.) 很快您会发现您不需要继承元素,只需汇总必要的行为(接触数,传导行为等)即可。

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

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