Derived class implementing multiple interfaces with a common function signature

前端 未结 4 1295
遥遥无期
遥遥无期 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条回答
  •  佛祖请我去吃肉
    2021-01-06 11:40

    First of all, I don't really understand the sense of your code.

    You need to know that only Interface1::common_func is implemented.

    Why don't you make Interface2 inherit from Interface1? I guess you want for both common_func methods to be equal.

    Example code (uses polymorphism):

    class Interface1 
    {
    public:
        virtual int common_func() = 0;
        virtual ~Interface1() {};
    };
    
    class Interface2 : public Interface1 {
    public:
        virtual int common_func() = 0;
        virtual int new_func() = 0;
        virtual ~Interface2() {};
    };
    
    class InterimClass : public Interface2 {
        public:
            virtual int common_func() {
                return 10;
            }
    };
    
    class MostDerivedClass : public InterimClass {
    public:
        virtual int new_func() {
            return 20;
        }
    };
    
    int test_func()
    {
        Interface1 * i1 = new MostDerivedClass;
        int x = i1->common_func();
        cout << "The value = " << x << endl;
    
        Interface2 * i2 = new MostDerivedClass;
        x = i2->common_func();
    
        return 0;
    }
    

提交回复
热议问题