码迷,mamicode.com
首页 > 其他好文 > 详细

运行时类型识别(RTTI)

时间:2019-12-31 17:05:57      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:cas   void   返回   基类指针   派生类   har   class   print   多态性   

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
  }

运行时类型识别(RTTI)

标签:cas   void   返回   基类指针   派生类   har   class   print   多态性   

原文地址:https://www.cnblogs.com/xiongyungang/p/12125345.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!