C++多重继承 - 为什么你不工作?
我正在尝试找出一个有趣的多重继承问题。
祖父母是一个具有多个方法的接口类:
class A
{
public:
virtual int foo() = 0;
virtual int bar() = 0;
};
然后是部分完成该接口的抽象类。
class B : public A
{
public:
int foo() { return 0;}
};
class C : public A
{
public:
int bar() { return 1;}
};
我想要使用的类继承自两个父类,并通过 using 指令指定应该来自何处的方法:
class D : public B, public C
{
public:
using B::foo;
using C::bar;
};
当我尝试实例化 DI 时,会因尝试实例化抽象类而出现错误。
int main()
{
D d; //<-- Error cannot instantiate abstract class.
int test = d.foo();
int test2 = d.bar();
return 0;
}
有人可以帮助我理解这个问题以及如何最好地利用部分实现吗?
I am trying to figure out an interesting multiple inheritance issue.
The grandparent is an interface class with multiple methods:
class A
{
public:
virtual int foo() = 0;
virtual int bar() = 0;
};
Then there are abstract classes that are partially completing this interface.
class B : public A
{
public:
int foo() { return 0;}
};
class C : public A
{
public:
int bar() { return 1;}
};
The class I want to use inherits from both of the parents and specifies what method should come from where via using directives:
class D : public B, public C
{
public:
using B::foo;
using C::bar;
};
When I try to instantiate a D I get errors for trying to instantiate an abstract class.
int main()
{
D d; //<-- Error cannot instantiate abstract class.
int test = d.foo();
int test2 = d.bar();
return 0;
}
Can someone help me understand the problem and how to best make use of partial implementations?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你没有钻石继承权。
D
的B
和C
基类各有自己的A
基类子对象,因为它们不是虚拟继承的来自A
。因此,在
D
中,实际上需要实现四个纯虚成员函数:A::foo
和A::bar
来自B
以及来自C
的A::foo
和A::bar
。您可能想使用虚拟继承。类声明和基类列表如下所示:
如果您不想使用虚拟继承,那么您需要重写
D
中的其他两个纯虚函数:You don't have diamond inheritance. The
B
andC
base classes ofD
each have their ownA
base class subobject because they do not inherit virtually fromA
.So, in
D
, there are really four pure virtual member functions that need to be implemented: theA::foo
andA::bar
fromB
and theA::foo
andA::bar
fromC
.You probably want to use virtual inheritance. The class declarations and base class lists would look like so:
If you don't want to use virtual inheritance then you need to override the other two pure virtual functions in
D
:您需要将基类设为
虚拟
,以便它们能够正确继承。一般规则是所有非私有成员函数和基类都应该是虚拟的,除非您知道自己在做什么并且想要禁用该成员/基类的正常继承。You need to make your base classes
virtual
in order for them to inherit properly. The general rule is that all non-private member functions and base classes should bevirtual
UNLESS you know what you're doing and want to disable normal inheritance for that member/base.