zoukankan      html  css  js  c++  java
  • 运行时类型识别(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
      }
    
  • 相关阅读:
    互联网商业数据分析(二十七):运营分析(三)用户分层
    鲲鹏服务器上跑dpdk kni bug
    dpdk 网卡顺序
    dpvs ipvsadm.c:114:10: fatal error: popt.h: No such file or directory
    dpvs keepalived编译出错
    ps查看线程所在的cpu + pstack 线程+ strace 线程
    查看内核模块加载时参数
    dpdk kni二
    dpdk eal 参数
    dpdk project gdb
  • 原文地址:https://www.cnblogs.com/xiongyungang/p/12125345.html
Copyright © 2011-2022 走看看