[英]Derived classes derived traits
Class B
has some group of methods trait1
. B
类具有一些方法trait1
。 Class B1
and C1
has similar group of methods trait2
. 类B1
和C1
具有类似的方法trait2
组。 trait2
is derived from trait1
. trait2
源自trait1
。
How can I implement this? 我该如何实施? I was going to move all of these trait
s methods out from the main hierarchy into some separate one. 我打算将所有这些trait
方法从主层次结构移到一些单独的方法中。 Then derive B
, B1
and C1
from appropriate trait. 然后根据适当的性状得出B
, B1
和C1
。 But then I realized that there would be a problem with inheriting B1
from B
because B1
would have trait1
too. 但是后来我意识到从B
继承B1
会有问题,因为B1
也将具有trait1
。
Now I think I can have some field of type, say, TraitBase
, and initiate it with appropriate ctor of type either trait1
or trait2
. 现在,我想我可以拥有一个类型为TraitBase
,并使用trait1
或trait2
类型的适当ctor来启动它。 But I don't like the idea that I should have a field so my class has some special behaviour. 但是我不喜欢应该有一个领域,这样我的班级会有一些特殊的行为。 May be there is another solution? 可能还有其他解决方案吗? Thank you. 谢谢。
UPDATE 更新
I mean class B
has some feature, which is derived in B1
. 我的意思是B
类具有某些功能,该功能是从B1
派生的。 C1
should have the feature, which class B1
has. C1
应该具有B1
类具有的功能。
class B
{
virtual foo1();
virtual foo2();
virtual trait_method1(); //implementation 1
virtual trait_method2(); //implementation 1
};
class B1 : public B
{
virtual foo1();
virtual foo2();
virtual trait_method1(); //implementation 2
virtual trait_method2(); //implementation 2
};
class C1 : public C
{
virtual bar1();
virtual bar2();
trait_method1(); //implementation 2
trait_method2(); //implementation 2
};
Your problem may be solved by virtually inheriting from trait1: 您的问题可以通过实际上继承trait1来解决:
class trait2 : virtual public trait1{} class B : public A, virtual public trait1{} class B1 : public B, public trait2{} class C1 : public C, public trait2{}
However, this design only makes sense if class trait1 is stateless. 但是,只有类trait1是无状态的,此设计才有意义。 If not, consider different designs, maybe Bridge pattern. 如果没有,请考虑其他设计,也许是桥接模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.