尝试编译代码时出现编译错误。
错误是这样的:

multi.cc: In function ‘int main()’:
multi.cc:35: error: cannot declare variable ‘mdc’ to be of abstract type ‘MostDerivedClass’
multi.cc:27: note:   because the following virtual functions are pure within ‘MostDerivedClass’:
multi.cc:13: note:  virtual int Interface2::common_func()
multi.cc:36: error: request for member ‘common_func’ is ambiguous
multi.cc:13: error: candidates are: virtual int Interface2::common_func()
multi.cc:21: error:                 virtual int InterimClass::common_func()

这是我的代码:
class Interface1 {
public:
    virtual int common_func() = 0;
    virtual ~Interface1() {};
};

class Interface2 {
public:
    virtual int common_func() = 0;
    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;
    }
};

int main() {
    MostDerivedClass mdc;
    int x = mdc.common_func();
    cout << "The value = " << x << endl;

    Interface2 &subset_of_funcs = dynamic_cast<Interface2 &>(mdc);
    x = subset_of_funcs.common_func();
}

我的问题:
  • 如何告诉编译器InterimClass已经实现了common_func(),InterimClass是MostDerivedClass的基类?
  • 还有另一种解决我的问题的方法吗?我真正想做的是能够从Interface2调用common_func。我正在使用一些具有接口(interface)1中大量方法的遗留代码。在我的新代码中,我只想调用一小部分这些Interface1函数,以及一些我需要添加的函数。
  • 最佳答案

    无论如何,您都需要在common_func()中定义一个MostDerivedClass,以满足您对Interface2的继承

    你可以尝试像

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

    如果您无法更改第一个Interface1,这将非常有用

    如果要在类之间建立真正的继承关系,则需要遵循Lol4t0建议。从Interface1提取一个父类(super class),并使这个新创建的类的Interface2成为子类。范例:
    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;
        }
    };
    

    08-05 21:59