zoukankan      html  css  js  c++  java
  • C++基础-类型转换-static_cast(基本类型转换) reinterpret_cast(指针类型转换) const_cast(const数据转换) dynamic_cast(父类子类转换)

    1.static_cast基本类型转换

    int main1()
    {
        //printf("%d", 10.2);
        //printf("%f", (float)1); //printf不会完成数据类型转换
        //printf("%d", static_cast<int>(10.2)); //默认转换
        printf("%f", static_cast<float >(1));
    }

    2.reinterpret_cast(指针类型转换)

    int main2()
    {
        int *pint = new int(1);
        char *pch = reinterpret_cast<char*>(pint); //指针类型转换  i
    
        for(int i = 0; i < 4; i++)
        {
            //显示数据,
            cout << static_cast<int>(*(pch + i)) << " "<< reinterpret_cast<void*>(pch + i) << endl;
        }
        cin.get();
    }

    3.const_cast(const数据类型转换)

    int main3()
    {
        int num[5] = {1, 2, 3, 4, 5};
        const int *p = num;
        //int *pint =reinterpret_cast<cint*>(int*)(p); reinterpret_cast不适于const
        int *pint = const_cast<int*>(p);
        for(int i = 0; i < 5; i++)
        {
            cout << pint[i] << " " << reinterpret_cast<void*>(pint + i) << endl;
        }
        cin.get();
    }

    4.dynamic_cast(父类子类转换)

    //父类
    class huahua
    {
    public:
        int hua1;
        virtual void run()
        {
            cout << "huahua is running" << endl;
        }
    };
    //子类
    class xiaohua: public huahua
    {
    public:
        int xiaohua1;
        void run() override
        {
            cout << "xiaohuahua is playing" << endl;
        }
    };
    
    int main()
    {
        huahua *pfu = new huahua;
        xiaohua *pzi = new xiaohua; //创建一个父类对象以及子类
        pfu->run();
        pzi->run();
    //    huahua *phua = dynamic_cast<huahua*>(pzi); //子类对象转换为父类指针
    //    cout << reinterpret_cast<void*>(phua) << endl;
    //    phua->run();
        xiaohua *pxiaohua = dynamic_cast<xiaohua*>(pfu);
        cout << reinterpret_cast<void*>(pxiaohua) << endl;
        if(pxiaohua != nullptr)
        {
            pxiaohua->hua1 = 10; //访问子类继承父类对象的变量
            pxiaohua->xiaohua1 = 10;
            pxiaohua->run(); //子类的对象
            (*pxiaohua).huahua::run(); //子类中间父类的方法
        }
    }
  • 相关阅读:
    26 playbooke(二)
    25 playbook(一)
    23 ansible模块2
    23 ansible模块(一)
    22 Ansible相关工具、ansible、ansible-vault、ansible-console、ansible-galaxy
    21 Ansible安装与主机清单的编写
    Druid.jar包
    Servlet--request
    mysql-myini配置
    global,tornado的write_error,tornado的中间件的写法
  • 原文地址:https://www.cnblogs.com/my-love-is-python/p/15008917.html
Copyright © 2011-2022 走看看