其他分享
首页 > 其他分享> > 运行时类型识别(RTTI)

运行时类型识别(RTTI)

作者:互联网

dynamic_cast转换

dynamic_cast执行两步操作,先验证转换是否有效,有效则进行实际转换

class Base
{
public:
  virtual void fun1(void){printf("this is Base fun1().\n");}
  virtual void fun2(void){printf("this is Base fun2().\n");}
  virtual void fun3(void){printf("this is Base fun3().\n");}
};

class Derive : public Base
{
public:
  virtual void fun1(void){printf("this is Derive fun1().\n");};
  virtual void fun2(void){printf("this is Derive fun2().\n");};
  virtual void fun3(void){printf("this is Derive fun3().\n");};
};

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 ) \n");  // nok
  }

  if (typeid(*pBaseToDerive) == typeid(Derive))
  {
    printf("typeid(*pBaseToDerive) == typeid(Derive) \n"); // ok
  }

标签:typeid,Derive,fun1,void,识别,Base,printf,类型,RTTI
来源: https://www.cnblogs.com/xiongyungang/p/12125345.html