• 现代C++学习笔记之二入门篇2,数据转换


    static_cast:    这种强制转换只会在编译时检查。 如果编译器检测到您尝试强制转换完全不兼容的类型,则static_cast会返回错误。 您还可以使用它在基类指针和派生类指针之间强制转换,但是,编译器在无法分辨此类转换在运行时是否是安全的。

    dynamic_castdynamic_cast在运行时检查基类指针和派生类指针之间的强制转换。 dynamic_cast 是比 static_cast 更安全的强制类型转换,但运行时检查会带来一些开销。

    const_cast:    const_cast转换为 const 的变量,或者将非 const 变量转换为 const。 通过使用这个操作符强制转换 const 就像使用C样式转换一样容易出错,不同之处在于使用const-cast 不太可能意外地执行转换。 有时候你只能强制转换 const 的变量,例如,传递 const 变量到一个非 const 参数的函数中。 

     void Func(double& d) { ... }
       void ConstCast()
       {
          const double pi = 3.14;
          Func(const_cast<double&>(pi)); //No error.
       }
    const_cast

    reinterpret_cast允许将任何指针转换为任何其他指针类型。 也允许将任何整数类型转换为任何指针类型以及反向转换。

     const char* str = "hello";
       int i = static_cast<int>(str);//error C2440: 'static_cast' : cannot
                                     // convert from 'const char *' to 'int'
       int j = (int)str; // C-style cast. Did the programmer really intend
                         // to do this?
       int k = reinterpret_cast<int>(str);// Programming intent is clear.
                                          // However, it is not 64-bit safe.
    reinterpret_cast
  • 相关阅读:
    python kivy 简单入门
    django 入门实例
    window docker安装
    apache进程和用户请求的关系
    php cookie工作原理
    react-router 简单的nginx配置
    node单线程支撑高并发原理(node异步I/O)
    知识图谱
    java
    java
  • 原文地址:https://www.cnblogs.com/yanhuiw/p/3813783.html
Copyright © 2020-2023  润新知