C++ Multiple Inheritance - why you no work?

前端 未结 2 794
面向向阳花
面向向阳花 2021-01-12 03:53

I am trying to figure out an interesting multiple inheritance issue.

The grandparent is an interface class with multiple methods:

class A
{
public:
          


        
2条回答
  •  迷失自我
    2021-01-12 04:30

    You don't have diamond inheritance. The B and C base classes of D each have their own A base class subobject because they do not inherit virtually from A.

    So, in D, there are really four pure virtual member functions that need to be implemented: the A::foo and A::bar from B and the A::foo and A::bar from C.

    You probably want to use virtual inheritance. The class declarations and base class lists would look like so:

    class A
    class B : public virtual A
    class C : public virtual A
    class D : public B, public C
    

    If you don't want to use virtual inheritance then you need to override the other two pure virtual functions in D:

    class D : public B, public C
    {
    public:
        using B::foo;
        using C::bar;
    
        int B::bar() { return 0; }
        int C::foo() { return 0; }
    };
    

提交回复
热议问题