• C++:转换函数和标准转换函数的意义


    C++转换函数

    C++标准转换函数

       编译时转换:reinterpret_cast、const_cast、static_cast

       运行时候转换:dynamic_cast

    1、reinterpret_cast

         reinterpret_cast(expression)

         将重新解释类型,不同类型指针和整型之间的相互转换,没有进行二进制的转换。

         2、const_cast

         const_cast( expression)

         const常量与普通变量之间的相互转换,

         注意:不能对非指针 或 非引用的 变量进行转换

         3、static_cast

         static_cast(expression)

         主要用于基本类型间的相互转换,和具有继承关系间的类型转换

         4、dynamic_cast

         dynamic_cast(expression)

         只有类中含有虚函数才能用dynamic_cast,仅能在继承类对象间转换(转指针或引用)

         dynamic_cast具有类型检查的功能,比static_cast更安全。

    标准转换函数意义:

    使转换代码更加明显,方便后期调试.

    提供C语言强转不支持的某些操作   

    代码如下:

    #include
    using namespace std;

    void test01()
    {
        float f1 = 3.456;
        int num = (int)f1;

        int *p = #
        char *q = (char*)p;

        cout << num << endl;
        cout << *q << endl;
    }

    void test02()
    {
        int num = 0x123456;
        //int *p = (int*)num;
        int *p1 = reinterpret_cast(num);

        int *p2 = #
        cout << p2 << endl;
        long num2 = reinterpret_cast(p2);
        cout << num2 << endl;

        //char *p3 = NULL;
        //long num3 = reinterpret_cast(p3);

        cout << *p1 << endl;
    }

    void test03()
    {
        const int a = 34;
        int *p = const_cast(&a);

        int &r_a1 = const_cast(a);
        //int &r_a1 = a;

        r_a1 = 78;
        cout << *p  << endl;
        cout << r_a1 << endl;
        cout << a << endl;
    }

    class Base
    {};
    class Son:public Base
    {};

    void test04()
    {
        int num = static_cast('a');
        cout << num << endl;

        Base b1;
        Son s1;

        b1 = s1;
        //s1 = static_cast(b1);   //error
        
        Base *p_b = NULL;
        Son *p_s = NULL;

        //p_s = p_b;   //error!
        p_s = static_cast(p_b);  //right
    }

    int main()
    {
        test04();
        return 0;
    }
     

  • 相关阅读:
    Hadoop1_hadoop概览
    【网络】计算机网络基础
    基于 IntelliJ 的 IDE 将提供 Wayland 支持
    【力扣-每日一题】213. 打家劫舍 II
    毕业设计之基于Vue的数据可视化平台
    【Tensorflow 2.12 电影推荐项目搭建】
    同学苹果ios的ipa文件应用企业代签选择签名商看看这篇文章你再去吧
    小程序图片报错替换
    uni-app 之 vue语法
    AGV|RGV小车RFID传感读卡器CK-G06A开发与用户手册技术说明
  • 原文地址:https://blog.csdn.net/qq_63626307/article/details/126842426