C++中的数据类型强制转换
时间: 2024-06-13 08:06:51 浏览: 18
C++中有四种命名的强制类型转换操作符:static_cast、reinterpret_cast、const_cast、dynamic_cast。
1. static_cast:用于非多态类型的转换,如基本数据类型之间的转换,具有较高的安全性。例如将int类型转换为double类型:
```c++
int a = 10;
double b = static_cast<double>(a);
```
2. reinterpret_cast:用于将一个指针转换为其他类型的指针,甚至可以将一个指针转换为整数类型,但是不保证转换的安全性。例如将int类型的指针转换为char类型的指针:
```c++
int a = 97;
char *p = reinterpret_cast<char*>(&a);
cout << *p << endl; // 输出:a
```
3. const_cast:用于将const类型转换为非const类型,具有较高的安全性。例如将const int类型转换为int类型:
```c++
const int a = 10;
int b = const_cast<int&>(a);
```
4. dynamic_cast:用于将基类指针或引用转换为派生类指针或引用,具有较高的安全性。例如将基类指针转换为派生类指针:
```c++
class Base {
public:
virtual void func() {}
};
class Derived : public Base {};
Base *p = new Derived;
Derived *q = dynamic_cast<Derived*>(p);
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)