检查对象的类型是否继承自特定的类

检查对象的类型是否继承自特定的类

问题描述:

在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
}