Multiple Inheritance from two derived classes

后端 未结 5 1311
清酒与你
清酒与你 2020-11-30 08:55

I have an abstract base class which acts as an interface.

I have two \"sets\" of derived classes, which implement half of the abstract class. ( one \"set\" defines t

5条回答
  •  心在旅途
    2020-11-30 09:18

    It looks like you want to do virtual inheritance. Whether that turns out to actually be a good idea is another question, but here's how you do it:

    
    class AbsBase {...};
    class AbsInit: public virtual AbsBase {...};
    class AbsWork: public virtual AbsBase {...};
    class NotAbsTotal: public AbsInit, public AbsWork {...};
    

    Basically, the default, non-virtual multiple inheritance will include a copy of each base class in the derived class, and includes all their methods. This is why you have two copies of AbsBase -- and the reason your method use is ambiguous is both sets of methods are loaded, so C++ has no way to know which copy to access!

    Virtual inheritance condenses all references to a virtual base class into one datastructure. This should make the methods from the base class unambiguous again. However, note: if there is additional data in the two intermediate classes, there may be some small additional runtime overhead, to enable the code to find the shared virtual base class.

提交回复
热议问题