C++的类型转换
1. 自动类型转换(隐式转换)
- 赋值符号右边类型往左边类型转换
int a = 3.14;
- 实参类型往形参类型转换
int f(int a);<br />f(3.14);
- 短类型往长类型转换
char, short -> int -> unsigned -> long -> double
-
2. 强制类型转换
2.1. 原因
有时自动转换不能满足需要。
C++语法更严格,不允许指针间自动转换。
int *p = malloc(4); //C++报错
int *p = (int *)malloc(4); //ok
2.2. C风格
(类型名) 表达式 ```c (int)3.14int b = 0x12345678; //int -> char char p1 = (char )&b;
//&a的类型const int const int a = 888; int p = (int *)&a;
<a name="rGq9p"></a>
## 2.3. C++风格
- **_基本类型之间的转换,对象的静态向下转型 _**
- 格式:<br />`static_cast<T>(express);`<br />eg:<br />`static_cast<int>(3.14);`
- **_指针与指针之间,指针与整数之间 _**
- 格式:<br />`reinterpret_cast<T>(express);`<br />eg:<br />`int a = 0x1234678; reinterpret_cast<char *>(&a);`
- **_去掉const限制 _**
- 格式:<br />`const_cast<T>(express);`<br />eg:<br />`const int n = 88; const_cast<int *>(&n);`
- **_对象的动态向下转型 _**
- 格式:<br />`dynamic_cast<T>(express);`
<a name="pWaGU"></a>
# 3. 总结
- C类型转换不仅可以用于基本类型、指针类型,还可以用于类之间的转换,涉及类的转换用C风格转换,否则用C风格转换。
<a name="jGHbh"></a>
# 4. 示例代码
```cpp
#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, char const *argv[]) {
cout << (double)340 / 1000 << endl; // 0.34 -> 0
//cout << (int)3.14 << endl;
cout << "static_cast : " << static_cast<int>(3.14) << endl;
int a = 0x12345678;
char *p1 = NULL;
//p1 = (char *)&a;
p1 = reinterpret_cast<char *>(&a);
cout << "reinterpret_cast : " << *p1 << endl;
volatile const int b = 888;
int *p2 = NULL;
//p2 = (int *)&b;
p2 = const_cast<int *>(&b);
*p2 = 999;
cout << "const_cast : " << b << endl;
return 0;
}