• c++类型转换static_cast dynamic_cast const_cast reinterpret_cast


    1.static_cast(编译时进行类型检查)

    static_cast < type-id > ( expression ) 将expression转换为type-id类型  但没有在运行时检查来保证转换的安全性

    用法:

    • 用于基本数据类型之间的转换
    • 把空指针转换成目标类型
    • 把任意类型转换成空类型
    • 用于类层次结构中的父类和子类之间的指针和引用类型转换
    1. #include
    2. using namespace std;
    3. class Date{
    4. public:
    5. void fun()
    6. {
    7. cout<<"Date......"<
    8. }
    9. };
    10. class Son:public Date{
    11. public:
    12. void fun()
    13. {
    14. cout<<"Son..........."<
    15. }
    16. };
    17. int main()
    18. {
    19. char a='A';
    20. int b=static_cast<int>(a);//基本数据类型转换
    21. cout<
    22. //将空指针转换成目标类型
    23. void *p=static_cast<void*>(&a);
    24. int *pd=static_cast<int*>(p);
    25. cout<<*pd<
    26. //父类的指针和引用
    27. Date* parent=static_cast(new Son);//向上转换
    28. Son*child=static_cast(new Date);//向下转换 不安全 (调用属于Son类而不是Date类的函数可能会导致访问冲突。)
    29. 为什么不安全?
    30. 用Son访问子类有父类没有的成员,就会出现访问越界的错误
    31. return 0;
    32. }

    2.dynamic_cast关键字(运行时类型检查)

    dynamic_cast主要用于类层次结构中父类和子类之间指针和引用的转换,由于具有运行时类型检查,

    因此可以保证下行转换的安全性,何为安全性?

    即转换成功就返回转换后的正确类型指针,如果转换失败,则返回NULL,之所以说static_cast在下行转换时不安全,是因为即使转换失败,它也不返回NULL。

    上行转换同样

     

    3.const_cast < type-id > ( expression )

    const_cast运算符可用于从类中删除const、volatile和__unaligned属性。

    • 常量指针被转化成非常量指针,并且仍然指向原来的对象;
    • 常量引用被转换成非常量引用,并且仍然指向原来的对象;
    • 常量对象被转换成非常量对象。
    1. #include
    2. using namespace std;
    3. class B{
    4. public:
    5. int a=10;
    6. };
    7. int main()
    8. {
    9. const B ob;
    10. //ob.a=20;//会报错 因为ob为常对象 内容不能被修改
    11. cout<
    12. B* ob1=const_cast(&ob);
    13. ob1->a=30;
    14. cout<a<
    15. return 0;
    16. }

    reinterpret_cast < type-id > ( expression )

     reinterpret_cast后的尖括号中的type-id类型必须是一个指针、引用、算术类型、函数指针或者成员指针。它可以把一个指针转换成一个整数,也可以把一个整数转换成一个指针。

     

  • 相关阅读:
    在旭日X3派开发板上使用USB Wifi来提高网络速度
    猿创征文|十 BLE协议之L2CAP
    二、鼎捷T100之MDS(Master Demand Schedule)计算
    【校招VIP】java语言考点之垃圾回收算法
    WPF的路由事件
    算法:(八)树
    Elasticsearch查询
    SpringMVC源码分析(四)请求流程分析
    把Android手机变成电脑摄像头
    C++高频面试题总结
  • 原文地址:https://blog.csdn.net/weixin_58389786/article/details/126419778