“进口”从基类定义一个函数来实现抽象接口(在C ++中的多重继承) [英] "import" a definition of a function from a base class to implement abstract interface (multiple inheritance in C++)

查看:113
本文介绍了“进口”从基类定义一个函数来实现抽象接口(在C ++中的多重继承)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个继承自两个基类的类(多继承)。基础类A 是抽象的,声明一个纯虚函数 foo ,其他基础 声明并实现非常相同签名的函数 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 {};

我想使用 foo 从我的派生类C 中的类B 但是,如果我没有在我的派生类C 中第二次实现函数 foo ,我不能实例化任何对象(它仍然是抽象的)。虚拟继承在这里不如预期的帮助(类A 类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).

我想知道是否有一种方法可以从类B中导入 foo / code>转换为 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.

当然是设计的。我想在类B 中实现 foo 的原因是我想得到 class D:并使用 B类执行 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 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.

推荐答案

p>在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆