zoukankan      html  css  js  c++  java
  • C++类型转换

    1、static_cast
    可以将子类和基类互相转换,只验证两者类型是否相关。如:
    子类到基类:
    CBase * pBase = new CDerived();
    CDerived * pDerived = static_cast<CDerived*>(pBase);//ok;

    基类到子类:
    CBase * pBase = new CBase();
    CDerived * pDerived = static_cast<CDerived*>(pBase);//compiled success,but error on running.

    不相关类型:
    CBase * pBase = new CDerived();
    CUnrelated * pUnrelated = static_cast<CUnrelated*>(pBase);//error. can't compiled success.


    2、dynamic_cast
    这种转换是在实际运行时执行检查,如果对象确实可以转换为该类型,他就能转换成功,而不管这两个类型之间有没有继承关系。如:
    struct B1{
        virtual ~B1(){}
    };
    struct B2{
        virtual ~B2(){}
        void m(){}
    };
    struct D1 : B1, B2{};
    int main()
    {
        D1 d;
        B1* pb1 = &d;
        B2* pb2 = dynamic_cast<B2*>(pb1);//ok
        //if(pb2)
        // pb2->m();
        B2* pb22 = static_cast<B2*>(pb1);  //error,can't compile success.
        return 0;
    }
    上述定义中可以看到,B1和B2是不相关的类,从L1可以看到,dynamic_cast允许这种转换:只要B1存在多态方法.L2将编译失败,static_cast并不允许两个完全不相干的类互相转换.


    3、reinterpret_cast
    强制类型转换,而不关心两个类型是否相关。如:
    CBase * pBase = new CBase();
    CUnrelated * pUnrelated = reinterpret_cast<CUnrelated*>(pBase);//ok, can compile success. maybe will throw error on running.


    4、const_cast
    关闭对象的访问修饰符const。如:
    CSomeClass
    {
          public:
                void DisplayMembers();//should define as const.
    }

    void DisplayAllData(const CSomeClass & mData)
    {
          mData.DisplayMembers();//compile failure, because we can't call a non const method on a const variable
          CSomeClass & refData = const_cast<CSomeClass&>(mData);
          refData.DisplayMembers();//compile success. close the const limitation.
    }

  • 相关阅读:
    解决pip3的ImportError: cannot import name 'main'
    linux 安装Python3.6
    Linux安装redis和部署
    redis密码管理
    CentOS7使用firewalld打开关闭防火墙与端口
    scrapy 从Windwos平台移植到 Linux平台之实操
    Linux 环境下安装Maven
    解决:安装Jenkins时web界面出现该jenkins实例似乎已离线
    持续集成工具Jenkins结合SVN的安装和使用
    Linux下的SVN服务器搭建
  • 原文地址:https://www.cnblogs.com/AndyGe/p/1555920.html
Copyright © 2011-2022 走看看