简体   繁体   English

多重继承和多态

[英]multiple inheritance and polymorphism

my dizzyCreature class inherits from both a creature class and a dizzy class. 我的dizzyCreature类继承自creature类和dizzy类。 It is also part of a polymorphic collection of creature classes. 它也是creature类的多态集合的一部分。 If I know that my object in the creature class is a dizzyCreature , is there a way to call a function from the dizzy class? 如果我知道我的creature类中的对象是dizzyCreature ,是否可以从dizzy类中调用函数? I have tried 我努力了

creature[2].dizzyCreature::someFunction();

and

dizzyCreature::creature[2].someFunction();

and neither works. 都行不通。 Any ideas? 有任何想法吗?

If I understand correctly what you have is something like this: list<Creature*> . 如果我正确理解您所拥有的是这样的: list<Creature*> This list contains some dizzyCreature instances. 此列表包含一些dizzyCreature实例。 On those instances you want to call methods of dizzy class. 在那些实例上,您要调用dizzy类的方法。 If this is the objective then you can use dynamic_cast to achieve this. 如果这是目标,则可以使用dynamic_cast来实现。 Lets say you have Create* pCreature then you can do: 假设您拥有Create* pCreature则可以执行以下操作:

dizzyCreature* pDizzyCreature = dynamic_cast<dizzyCreature*>(pCreature);
if(pDizzyCreature )
{
  pDizzyCreature->someDizzyClassMethod();
}

You need to first check if the class is of the correct type, then cast it using dynamic_cast , as has already been suggested. 您需要首先检查类的类型是否正确,然后如建议的那样使用dynamic_cast对其进行dynamic_cast This solution is elegant since the dynamic cast itself does the type-checking - ie it will return NULL if you try to make an invalid cast. 这种解决方案很不错,因为动态类型转换本身会进行类型检查-即,如果您尝试进行无效的类型转换,它将返回NULL。 (There is no need to use typeid ) (无需使用typeid

As a side note, if I were you, I'd attempt to do whatever it is you're trying to do without multiple inheritance if possible. 附带说明一下,如果我是您,那么我将尽可能地尝试您尝试做的事情而没有多重继承。 Multiple inheritance can open up a whole can of worms and is best avoided unless there is no other alternative. 多重继承可以打开一堆蠕虫,除非没有其他选择,否则最好避免。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM