运行时类型识别(RTTI)
Posted xiongyungang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了运行时类型识别(RTTI)相关的知识,希望对你有一定的参考价值。
dynamic_cast转换
dynamic_cast执行两步操作,先验证转换是否有效,有效则进行实际转换
class Base
{
public:
virtual void fun1(void){printf("this is Base fun1().
");}
virtual void fun2(void){printf("this is Base fun2().
");}
virtual void fun3(void){printf("this is Base fun3().
");}
};
class Derive : public Base
{
public:
virtual void fun1(void){printf("this is Derive fun1().
");};
virtual void fun2(void){printf("this is Derive fun2().
");};
virtual void fun3(void){printf("this is Derive fun3().
");};
};
int _tmain(int argc, _TCHAR* argv[])
{
// 将基类指针转换为派生类指针
Base *pBase = new Derive();
// 转换失败dynamic_cast返回0
if (Derive *pDerive = dynamic_cast<Derive*>(pBase))
{
pDerive->fun1();
}
else
{
pBase->fun1();
}
delete pBase;
// 转换引用类型
// 如果转换引用类型失败,会抛出异常
Base &base = Derive();
try
{
Derive &derive = dynamic_cast<Derive&>(base);
derive.fun1();
}
catch (std::bad_cast)
{
}
return 0;
}
typeid操作符
类类型包含虚函数时,typeid的结果存在多态性
Base *pBase = new Base();
Base *pBaseToDerive = new Derive();
// pBaseToDerive 是Derive类型
if (typeid(*pBase) == typeid(*pBaseToDerive ))
{
printf("typeid(*pBase) == typeid(*pBaseToDerive )
"); // nok
}
if (typeid(*pBaseToDerive) == typeid(Derive))
{
printf("typeid(*pBaseToDerive) == typeid(Derive)
"); // ok
}
以上是关于运行时类型识别(RTTI)的主要内容,如果未能解决你的问题,请参考以下文章