“进口"从基类定义一个函数来实现抽象接口(C++ 中的多重继承) [英] "import" a definition of a function from a base class to implement abstract interface (multiple inheritance in C++)
问题描述
假设我们有一个继承自两个基类的类(多重继承).基class A
是抽象的,声明了一个纯虚函数foo
,另一个基class B
声明并实现了一个函数foo代码>完全相同的签名.
Say we have a class inheriting from two base classes (multiple inheritance). Base class A
is abstract, declaring a pure virtual function foo
, the other base class B
declares and implements a function foo
of the very same signature.
struct A
{
virtual void foo(int i) = 0;
};
struct B
{
virtual void foo(int i) {}
};
struct C : public A, public B {};
我想在派生的class C
中使用基础class B
的foo
实现.但是,如果我没有在派生的 class C
中第二次实现函数 foo
,我将无法实例化它的任何对象(它仍然是抽象的).虚拟继承在这里没有预期的帮助(class A
和 class B
没有公共基类).
I want to use the implementation of foo
from base class B
in my derived class C
. However, if I do not implement the function foo
a second time in my derived class C
, I cannot instantiate any object of it (it remains abstract). Virtual inheritance does not help here as expected (class A
and class B
have no common base class).
我想知道是否有一种方法可以将 foo
从 class B
的实现导入"到 class C
中,以免有重复相同的代码.
I wonder if there is a way to "import" the implementation of foo
from class B
into class C
in order not to have to repeat the same code.
上面的例子当然是人为的.我想在 class B
中实现 foo
的原因是我想派生 class D : public B
并使用 class B
s foo
的实现.我知道继承(主要)不是为了代码重用,但我仍然希望以这种方式使用它.
Above example is of course contrived. The reason I want implement foo
in class B
is that I want to derive class D : public B
and use class B
s implementation of foo
. I know that inheritance is not (primarily) intended for code reuse, but I'd still like to use it in that way.
推荐答案
在 Java 中,您的示例代码有效.在 C++ 中它没有.这些语言之间的细微差别.
In java, your sample code works. In C++ it doesn't. A subtle difference between those languages.
您在 C++ 中的最佳选择是通过转发到 B::foo() 来定义 C::foo():
Your best option in C++ is to define C::foo() by forwarding to B::foo():
struct C : public A, public B
{
virtual void foo(int i) { B::foo(i); }
};
这篇关于“进口"从基类定义一个函数来实现抽象接口(C++ 中的多重继承)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!