“导入”从基类定义函数来实现抽象接口(C 中的多重继承)

发布于 2024-09-10 23:51:10 字数 784 浏览 1 评论 0原文

假设我们有一个从两个基类继承的类(多重继承)。基类A是抽象的,声明了一个纯虚函数foo,另一个基类B声明并实现了一个函数foo code> 具有完全相同的签名。

struct A
{
  virtual void foo(int i) = 0;
};

struct B
{
  virtual void foo(int i) {}
};

struct C : public A, public B {};

我想在派生的 class C 中使用基类 B 中的 foo 实现。但是,如果我不在派生的 C 类中再次实现函数 foo,我就无法实例化它的任何对象(它仍然是抽象的)。虚拟继承在这里并没有像预期的那样有帮助(class Aclass B 没有公共基类)。

我想知道是否有一种方法可以将 foo 的实现从 class B 导入到 class C 中,以便不必重复相同的代码。

上面的例子当然是人为的。我想在 class B 中实现 foo 的原因是我想派生 class D : public B 并使用 class B code>s 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 {};

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).

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.

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 Bs 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寻梦旅人 2024-09-17 23:51:10

在 java 中,您的示例代码可以运行。在 C++ 中则不然。这些语言之间存在细微的差别。

C++ 中的最佳选择是通过转发到 B::foo() 来定义 C::foo():

struct C : public A, public B
{
  virtual void foo(int i) { B::foo(i); }
};

In java, your sample code works. In C++ it doesn't. A subtle difference between those languages.

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); }
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文