2012-04-12 26 views
0

在C++中使用多继承来表达图的好方法是什么?或者我需要在这种情况下使用多重继承?我不能只在基类中创建一个Child1和一个Child2实例并使用它们吗?C++中的多继承:在C++中使用多继承来表达图的好方法是什么?

enter image description here

+2

你想实现什么?从这个图表不清楚。如果要使用通用接口连接子实例,请将其放入基类中。 – 2012-04-12 07:31:04

+0

是的。我想连接子类。你能告诉我代码的大纲吗? – FlintOff 2012-04-12 07:32:27

+0

这取决于您想要如何连接子案例。 – juanchopanza 2012-04-12 07:39:48

回答

0

这是伪代码,但应该说明的层次:

解决方案1:

class IBaseInterface {} 

class Base : IBaseInterface {} 

class Child1 : Base {} 

class Child2 : Base {} 

解决方案2:

class IChildInterface {} 

class Base {} 

class Child1 : Base, IChildInterface {} 

class Child2 : Base, IChildInterface {} 
+0

在解决方案1:为什么有IBaseInterface? – FlintOff 2012-04-12 07:54:02

+0

因为接口在基类上,所以我这样调用它。这两个解决方案是有效的:具有连接基类中的子类的接口,以便子类继承它或从接口派生所有想要连接的子类。 – ChrisWue 2012-04-12 07:59:10

+0

是。从IW中派生出来的东西几乎总是安全的,所以你不需要做虚拟继承等等。 – 2012-04-12 08:12:36

0

“我不能只是创建基类中的Child1和Child2实例并使用它们?“

我想你正在努力实现的就是这个,不需要多重继承:

class IChildInterface {} 

class Base { IChildInterface* child; } 

class Child1: public IChildInterface 
class Child2: public IChildInterface