C++ 检查对象的类型是否继承自特定类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12963294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if the Type of an Object is inherited from a specific Class
提问by danijar
In C++, how can I check if the type of an object is inherited from a specific class?
在 C++ 中,如何检查对象的类型是否继承自特定类?
class Form { };
class Moveable : public Form { };
class Animatable : public Form { };
class Character : public Moveable, public Animatable { };
Character John;
if(John is 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.
在我的实现中,if
查询是对Form
列表的所有元素执行的。所有继承自类型的对象都Moveable
可以移动并需要处理其他对象不需要的对象。
回答by K-ballo
What you need is dynamic_cast
. In its pointer form, it will return a null pointer if the cast cannot be performed:
你需要的是dynamic_cast
。在其指针形式中,如果无法执行强制转换,它将返回一个空指针:
if( Moveable* moveable_john = dynamic_cast< Moveable* >( &John ) )
{
// do something with moveable_john
}
回答by juanchopanza
You are using private inheritance, so it is not possible to use dynamic_cast
to determine whether one class is derived from another. However, you can use std::is_base_of
, which will tell you this at compile time:
您正在使用私有继承,因此无法使用dynamic_cast
来确定一个类是否从另一个类派生。但是,您可以使用std::is_base_of
,它会在编译时告诉您:
#include <type_traits>
class Foo {};
class Bar : Foo {};
class Baz {};
int main()
{
std::cout << std::boolalpha;
std::cout << std::is_base_of<Foo, Bar>::value << '\n'; // true
std::cout << std::is_base_of<Bar,Foo>::value << '\n'; // false
std::cout << std::is_base_of<Bar,Baz>::value << '\n'; // false
}
回答by Science_Fiction
Run-time type information (RTTI) is a mechanism that allows the type of an object to be determined during program execution. RTTI was added to the C++ language because many vendors of class libraries were implementing this functionality themselves.
运行时类型信息 (RTTI) 是一种允许在程序执行期间确定对象类型的机制。RTTI 被添加到 C++ 语言中,因为许多类库供应商正在自己实现这个功能。
Example:
例子:
//moveable will be non-NULL only if dyanmic_cast succeeds
Moveable* moveable = dynamic_cast<Moveable*>(&John);
if(moveable) //Type of the object is Moveable
{
}