Implementing multiple interfaces in c++

前端 未结 4 1941
后悔当初
后悔当初 2020-11-28 15:43

I have the interface hierarchy as follows:

class A
{
public:
 void foo() = 0;
};

class B: public A
{
public:
void testB() = 0;
};

class C: public A
{
publi         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 16:26

    While I'd normally think twice before suggesting multiple inheritance. If your needs really aren't more complicated than you said, then just inherit both interface and implementation virtually.

    class A
    {
    public:
      void foo() = 0;
    };
    
    class B: virtual public A
    {
    public:
      void testB() = 0;
    };
    
    class C: virtual public A
    {
    public:
      void testC() = 0;
    };
    
    class AImpl : virtual public A
    {
     ...
    }
    
    class BImpl : virtual public B, virtual public AImpl
    {
     ...
    }
    

    The virtual inheritance will make sure there is only one sub-object A shared between B and AImpl. So you should be in the clear. The object size will increase, however. So if that's an issue, rethink your design.

提交回复
热议问题