Derived class implementing multiple interfaces with a common function signature

前端 未结 4 1279
遥遥无期
遥遥无期 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
    慢半拍i (楼主)
    2021-01-06 11:15

    Let the second interface be derived from the first interface, remove the declaration of virtual int common_func() = 0; from the second interface, & use the keyword virtual to guide the compiler to the implementation.

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

提交回复
热议问题