zoukankan      html  css  js  c++  java
  • 现代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
  • 相关阅读:
    [转]sql语句优化原则
    [Effective C++]构造/析构/赋值运算
    [Effective C++]定制new和delete
    [Effective C++]让自己习惯C++
    [C++ primer]联合:节省空间的类
    [C++ primer]类成员指针
    [C++ primer]运行时类型识别(RTTI)
    [APUE]fork后子进程的运行情况
    [C++ primer]优化内存分配
    [C++ primer]虚函数和纯虚函数
  • 原文地址:https://www.cnblogs.com/yanhuiw/p/3813783.html
Copyright © 2011-2022 走看看