コードをコンパイルしようとすると、コンパイルエラーが発生します。エラーは次のとおりです。
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();
}
私の質問:
common_func()がMostDerivedClassの基本クラスであるInterimClassによってすでに実装されていることをコンパイラに伝えるにはどうすればよいですか?
問題を解決する別の方法はありますか?私が本当にやりたいのは、Interface2からcommon_funcも呼び出せるようにすることです。Interface1で大量のメソッドを使用するレガシーコードを使用しています。新しいコードでは、これらのInterface1関数の小さなセットに加えて、追加する必要のあるいくつかの関数を呼び出したいだけです。