C++ 73 之 类型转换

#include <iostream>
#include <string>
using namespace std;

class Base01{};
class Son01 : public Base01{};
class neighbor01{};

int main()
{
    // 静态转换 static_cast
    // 变量的类型转换static_cast<目标类型>(要转换的变量)
    // char a = 'a';
    // int b = static_cast<int>(a);
    // cout << b << endl;

    // // 指针
    // Base01* base = NULL;
    // Son01* son = NULL;
    // neighbor01* neighbor = NULL;
    // // 将base父类转为son子类,向下类型转化,有不安全的隐患
    // Son01* son2 = static_cast<Son01*>(base);

    // // 将son子类转为base父类,向上类型转换,安全
    // Base01* base2 = static_cast<Base01*>(son);

    // 没有继承关系,指针转换失败
    // Base01* base2 = static_cast<Base01>(neighbor);


    // 动态转换 dynamic_cast 更安全转换

    // 不允许内置数据类型进行动态转换
    // char a = 'a';
    // int b = dynamic_cast<int>(a); // 报错


     // 指针
    // Base01* base = NULL;
    // Son01* son = NULL;
    // neighbor01* neighbor = NULL;
    // // 将base父类转为son子类,向下类型转化,有不安全的隐患
    // Son01* son2 = static_cast<Son01*>(base);

    // // 将son子类转为base父类,向上类型转换,安全
    // Base01* base2 = static_cast<Base01*>(son);

    // 没有继承关系,指针转换失败
    // Base01* base2 = static_cast<Base01>(neighbor);

    // 多态转化都是安全
    // 父类指针指向子类的对象
    // Base01* base = new Son01;

    // 将base父类转为son子类,向下类型转换,已经是多态了,所以安全
    


    // static_cast  dynamic_cast对比:
    // static_cast 不安全,父转子  子转父  都可以正常运行
    // dynamic_cast 安全: 父转子会报错,子转父可以正常运行
    // 只要是多态,就一定是安全的


    // const_cast 转换:不可以将非指针或非引用做const_cast转换

    // const int* p = NULL;
    // int* pp = const_cast<int*>(p);
    // const int* ppp = const_cast<const int*>(pp);

    // int num = 10;
    // int& numRef = num;
    // const int& num2 = const_cast<const int&>(numRef);
    // int& num3 = const_cast<int&>(num2);


    // 重新解释转换:不要使用! 最不安全的一种!
    // int a = 10;
    // int* p = reinterpret_cast<int*>(a);

    // Base01* base = NULL;
    // // 竟然能父转邻居 了解即可
    // neighbor01* lin = reinterpret_cast<neighbor01*>(base);

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值