C++ 四种强制类型转换
C++ 推荐用4个关键字转换,替代 C 语言粗暴的 (类型)变量,语义清晰、更安全。
1. static_cast 静态转换
- 编译期转换,不做运行时检查
- 适用:
基本数据类型转换(int/double/char)、父子类安全向上转型、void* 互转 - 不能去掉 const
示例:
double a = 3.14;
int b = static_cast<int>(a);
2. dynamic_cast 动态转换
- 运行时检查,安全向下转型
- 条件:基类必须有虚函数
- 指针失败返回
nullptr,引用失败抛异常
Base* p = new Son;
Son* s = dynamic_cast<Son*>(p);
3. const_cast 常量转换
- 唯一能去掉 const/volatile 的转换
- 只能修饰指针、引用,不能改变量类型
const int x = 10;
int* p = const_cast<int*>(&x);
4. reinterpret_cast 重解释转换
- 直接按二进制比特强制解释,不做任何安全检查
- 适用:指针 ↔ 整数、不同类型指针互转
int a = 10;
long long* p = reinterpret_cast<long long*>(&a);
面试口述
- static_cast:普通类型、父子类,编译期
- dynamic_cast:多态向下转,运行时安全检查
- const_cast:专门去掉 const
- reinterpret_cast:二进制暴力转换,不安全
221



被折叠的 条评论
为什么被折叠?



