Derived class implementing multiple interfaces with a common function signature

前端 未结 4 1284
遥遥无期
遥遥无期 2021-01-06 10:57

I\'m getting a compile error when I try to compile my code. The error is this:

multi.cc: In function ‘int main()’:
multi.cc:35: error: cannot declare variabl         


        
4条回答
  •  萌比男神i
    2021-01-06 11:30

    You need to define a common_func() anyway in MostDerivedClass to satisfy your inheritance from Interface2

    you can try something like

    virtual int common_func() {
        return InterimClass::common_func();
    }
    

    This is most useful if you cannot change the first Interface1

    If you want a real inheritance relationship between your classes you need to follow Lol4t0 advice. Extract a superclass from Interface1, and make Interface2 subclass of this newly created class. Example :

    class RootInterface{
    public :
        virtual int common_func() = 0;
        virtual ~RootInterface(){}
    };
    
    class Interface1 : public virtual RootInterface{
    public:
        virtual ~Interface1() {};
    };
    
    class Interface2 : public virtual RootInterface{
        public:
        virtual int new_func() = 0;
        virtual ~Interface2() {};
    };
    
    class InterimClass : public Interface1 {
        public:
        virtual int common_func() {
            return 10;
        }
    };
    
    class MostDerivedClass : public InterimClass, public Interface2 {
    public:
        virtual int new_func() {
            return 20;
        }
    };
    

提交回复
热议问题