A use for multiple inheritance?

后端 未结 12 1896
暖寄归人
暖寄归人 2020-11-29 07:29

Can anyone think of any situation to use multiple inheritance? Every case I can think of can be solved by the method operator

AnotherClass() { return this-&         


        
12条回答
  •  借酒劲吻你
    2020-11-29 08:05

    I had to use it today, actually...

    Here was my situation - I had a domain model represented in memory where an A contained zero or more Bs(represented in an array), each B has zero or more Cs, and Cs to Ds. I couldn't change the fact that they were arrays (the source for these arrays were from automatically generated code from the build process). Each instance needed to keep track of which index in the parent array they belonged in. They also needed to keep track of the instance of their parent (too much detail as to why). I wrote something like this (there was more to it, and this is not syntactically correct, it's just an example):

    class Parent
    {
        add(Child c)
        {
            children.add(c);
            c.index = children.Count-1;
            c.parent = this;
        }
        Collection children
    }
    
    class Child
    {
        Parent p;
        int index;
    }
    

    Then, for the domain types, I did this:

    class A : Parent
    class B : Parent, Child
    class C : Parent, Child
    class D : Child
    

    The actually implementation was in C# with interfaces and generics, and I couldn't do the multiple inheritance like I would have if the language supported it (some copy paste had to be done). So, I thought I'd search SO to see what people think of multiple inheritance, and I got your question ;)

    I couldn't use your solution of the .anotherClass, because of the implementation of add for Parent (references this - and I wanted this to not be some other class).

    It got worse because the generated code had A subclass something else that was neither a parent or a child...more copy paste.

提交回复
热议问题