zoukankan      html  css  js  c++  java
  • C++(四十五) — 类型转换(static_cast、dynamic_cast 、const_cast、reinterpreter_cast)

     0、总结

      (1)要转换的变量,转换前、转换后、转换后的结果。

      (2)一般情况下,避免进行类型转换。

    1、_static_cast(静态类型转换,int 转换为char)

       格式:TYPE B = static_cast<TYPE>(a)

       reinterpreter_cast(重新解释类型):专门用于指针类型的转换。

    void main()
    {
        double dpi = 3.1415;
        //int num1 = dpi;//默认自动类型转换,会提示 warning
        int num2 = static_cast<int>(dpi);//静态类型转换,在编译时会做类型检查,如有错误会提示
    
        // char* -> int*
        char* p1 = "hello";
        int* p2 = nullptr;
        //p2 = static_cast<int*>(dpi);// 转换类型无效,
        p2 = reinterpret_cast<int *>(p1);//相当于强制类型转化,指针类型
        cout << p1 << endl;//输出字符串
        cout << p2 << endl;//输出指针的首地址
    
        system("pause");
    }

    2、dynamic_cast(动态类型转化,如子类和父类之间的多态类型转换)

    #include <iostream>
    using namespace std;
    
    class Animal
    {
    public:
        virtual void cry() = 0;
    };
    class Dog :public Animal
    {
    public:
        virtual void cry()
        {
            cout << "wangwang" << endl;
        }
        void doHome()
        {
            cout << "kanjia" << endl;
        }
    };
    class Cat :public Animal
    {
    public:
        virtual void cry()
        {
            cout << "miaomiao" << endl;
        }
        void doHome()
        {
            cout << "keai" << endl;
        }
    };
    void playObj(Animal *base)
    {
        base->cry();
        //运行时的类型识别,
        //父类对象转换为子类对象
        Dog *pDog = dynamic_cast<Dog*>(base);//如果不是该类型,则返回值为null
        if (pDog != NULL)
        {
            pDog->doHome();
        }
        Cat *pCat = dynamic_cast<Cat*>(base);//如果不是该类型,则返回值为null
        if (pCat != NULL)
        {
            pCat->doHome();
        }
    }
    
    void main()
    {
        Dog d1;
        Cat c1;
        //父类对象转换为子类对象
        playObj(&d1);
        playObj(&c1);
        //子类对象转换为父类对象
        Animal *pBase = nullptr;
        pBase = &d1;
        pBase = static_cast<Animal *>(&d1);
    
        system("pause");
    }

    3、const_cast(去 const 属性)

       该函数把只读属性去除。

    p1 = const_cast<char*>(p);
  • 相关阅读:
    DBC的故事
    MDF,了解一下
    PAT A 1059 Prime Factors (25分)
    素数的判断与素数表的获取
    PAT A 1014 Waiting in Line (30分)
    n皇后问题(全排列+回溯)
    最长回文子串(c++)
    传输方式的分类
    OSI模型概述
    进制转换
  • 原文地址:https://www.cnblogs.com/eilearn/p/10987823.html
Copyright © 2011-2022 走看看