美文网首页
C++之数据类型转换

C++之数据类型转换

作者: 二进制人类 | 来源:发表于2022-10-25 08:50 被阅读0次

上下行转换

子类上行转换成父类

父类下行转换成子类

静态转换(static_cast)

 //1、基本类型转换(支持)
    double d=3.15;
    int num =static_cast<int>(d);

    //2、基本指针类型(引用)转换 (不支持)
    //int *p1 = static_cast<int *>(&d);

    //3、上行转换(支持  安全)
    Base *p2 = static_cast<Base *>(new Son);

    //4、下行转换(支持   不安全)
    Son *p3 = static_cast<Son *>(new Base);

    //5、不相关类型转换(不支持)
    //Base *p4 = static_cast<Base *>(new Other);

动态转换(dynamic_cast)

//1、基本类型转换(不支持)
    double d=3.15;
    //int num =dynamic_cast<int>(d);

    //2、基本指针类型(引用)转换 (不支持)
    //int *p1 = dynamic_cast<int *>(&d);

    //3、上行转换(支持  安全)
    Base *p2 = dynamic_cast<Base *>(new Son);

    //4、下行转换(不支持   不安全)
    //Son *p3 = dynamic_cast<Son *>(new Base);

    //5、不相关类型转换(不支持)
    //Base *p4 = dynamic_cast<Base *>(new Other);

常量转换(const_cast)

const和非const之间转换

//1、基本类型转换(不支持)
    const int num = 10;
    //int data = const_cast<int>(num);
    //int &data2 = const_cast<int>(num);

    int num2 = 10;
    //const int data3 = const_cast<const int>(num2);
    //const int &data4 = const_cast<const int>(num2);

    //2、基本指针类型的转换(支持)
    const int num3=10;
    int *p1 = const_cast<int *>(&num3);

    int num4 = 10;
    const int *p2 = const_cast<const int *>(&num4);

    //3、自定义类型转换 (支持)
    const Other ob3;
    Other &ob4 = const_cast<Other &>(ob3);

    Other ob5;
    const Other &ob6 = const_cast<const Other &>(ob5);

    //4、自定义类型指针 (支持)
    const Other ob1;
    Other *p3 = const_cast<Other *>(&ob1);

    Other ob2;
    const Other *p4 = const_cast<const Other *>(&ob2);

重新解释转换(reinterpret_cast)

类型C语言的强制类型转换。

//1、基本类型转换(不支持)
    double d=3.15;
    //int num =reinterpret_cast<int>(d);

    //2、基本指针类型(引用)转换 (支持)
    int *p1 = reinterpret_cast<int *>(&d);

    //3、上行转换(支持  安全)
    Base *p2 = reinterpret_cast<Base *>(new Son);

    //4、下行转换(支持 不安全)
    Son *p3 = reinterpret_cast<Son *>(new Base);

    //5、不相关类型转换(支持)
    Base *p4 = reinterpret_cast<Base *>(new Other);

相关文章

网友评论

      本文标题:C++之数据类型转换

      本文链接:https://www.haomeiwen.com/subject/jsxwzrtx.html