C++的类型转换

1. 自动类型转换(隐式转换)

  • 赋值符号右边类型往左边类型转换
    int a = 3.14;
  • 实参类型往形参类型转换
    int f(int a);<br />f(3.14);
  • 短类型往长类型转换
    char, short -> int -> unsigned -> long -> double
  • 低精度类型往高精度类型转
    float -> double

    2. 强制类型转换

    2.1. 原因

  • 有时自动转换不能满足需要。

  • C++语法更严格,不允许指针间自动转换。
    int *p = malloc(4); //C++报错
    int *p = (int *)malloc(4); //ok

    2.2. C风格


    (类型名) 表达式 ```c (int)3.14

    int b = 0x12345678; //int -> char char p1 = (char )&b;

//&a的类型const int const int a = 888; int p = (int *)&a;

  1. <a name="rGq9p"></a>
  2. ## 2.3. C++风格
  3. - **_基本类型之间的转换,对象的静态向下转型 _**
  4. - 格式:<br />`static_cast<T>(express);`<br />eg:<br />`static_cast<int>(3.14);`
  5. - **_指针与指针之间,指针与整数之间 _**
  6. - 格式:<br />`reinterpret_cast<T>(express);`<br />eg:<br />`int a = 0x1234678; reinterpret_cast<char *>(&a);`
  7. - **_去掉const限制 _**
  8. - 格式:<br />`const_cast<T>(express);`<br />eg:<br />`const int n = 88; const_cast<int *>(&n);`
  9. - **_对象的动态向下转型 _**
  10. - 格式:<br />`dynamic_cast<T>(express);`
  11. <a name="pWaGU"></a>
  12. # 3. 总结
  13. - C类型转换不仅可以用于基本类型、指针类型,还可以用于类之间的转换,涉及类的转换用C风格转换,否则用C风格转换。
  14. <a name="jGHbh"></a>
  15. # 4. 示例代码
  16. ```cpp
  17. #include <iostream>
  18. #include <cstdlib>
  19. using namespace std;
  20. int main(int argc, char const *argv[]) {
  21. cout << (double)340 / 1000 << endl; // 0.34 -> 0
  22. //cout << (int)3.14 << endl;
  23. cout << "static_cast : " << static_cast<int>(3.14) << endl;
  24. int a = 0x12345678;
  25. char *p1 = NULL;
  26. //p1 = (char *)&a;
  27. p1 = reinterpret_cast<char *>(&a);
  28. cout << "reinterpret_cast : " << *p1 << endl;
  29. volatile const int b = 888;
  30. int *p2 = NULL;
  31. //p2 = (int *)&b;
  32. p2 = const_cast<int *>(&b);
  33. *p2 = 999;
  34. cout << "const_cast : " << b << endl;
  35. return 0;
  36. }