dan*_*jar 9 c++ oop inheritance types
在C++中,如何检查对象的类型是否从特定类继承?
class Form { };
class Moveable : public Form { };
class Animatable : public Form { };
class Character : public Moveable, public Animatable { };
Character John;
if(John is moveable)
// ...
Run Code Online (Sandbox Code Playgroud)
在我的实现中,if查询在Form列表的所有元素上执行.继承自的所有类型的对象都Moveable可以移动并需要处理其他对象不需要的对象.
K-b*_*llo 25
你需要的是什么dynamic_cast.在其指针形式中,如果无法执行强制转换,它将返回空指针:
if( Moveable* moveable_john = dynamic_cast< Moveable* >( &John ) )
{
// do something with moveable_john
}
Run Code Online (Sandbox Code Playgroud)
jua*_*nza 11
您正在使用私有继承,因此无法使用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
}
Run Code Online (Sandbox Code Playgroud)
运行时类型信息(RTTI)是一种允许在程序执行期间确定对象类型的机制。RTTI 被添加到 C++ 语言中,因为许多类库供应商自己实现了此功能。
例子:
//moveable will be non-NULL only if dyanmic_cast succeeds
Moveable* moveable = dynamic_cast<Moveable*>(&John);
if(moveable) //Type of the object is Moveable
{
}
Run Code Online (Sandbox Code Playgroud)