本文介绍了检查对象的类型是否继承自特定的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C ++中,如何检查对象的类型是否继承自特定类?
In C++, how can I check if the type of an object is inherited from a specific class?
class Form { };
class Moveable : public Form { };
class Animatable : public Form { };
class Character : public Moveable, public Animatable { };
Character John;
if(John is moveable)
// ...
在我的实现中, if
查询是在 Form
列表的所有元素上执行的。从 Moveable
继承的所有类型的对象都可以移动并需要处理其他对象不需要的对象。
In my implementation the if
query is executed over all elements of a Form
list. All objects which type is inherited from Moveable
can move and need processing for that which other objects don't need.
推荐答案
您需要的是 dynamic_cast
。在其指针形式中,如果无法执行强制转换,它将返回空指针:
What you need is dynamic_cast
. In its pointer form, it will return a null pointer if the cast cannot be performed:
if( Moveable* moveable_john = dynamic_cast< Moveable* >( &John ) )
{
// do something with moveable_john
}
这篇关于检查对象的类型是否继承自特定的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!