static_cast
是 C++ 中最常用的 显式类型转换运算符之一,主要用于在类型安全的前提下进行 编译时的类型转换。
✅ 基本语法
static_cast<new_type>(expression)
new_type
:你想要转换成的目标类型。expression
:原始值或对象。
✅ 常见用途示例
1. 基本类型转换(int ⇋ float 等)
int a = 10;
float b = static_cast<float>(a); // int 转 float
2. 指针类型之间的转换(向上转换、向下转换)
class Base {};
class Derived : public Base {};
Derived d;
Base* bp = static_cast<Base*>(&d); // 安全:向上转换
⚠️ 向下转换(如 Base* → Derived*
)虽然语法允许,但需要你确保指针实际指向的是派生类对象,否则会出现 未定义行为:
Base* bp = new Derived();
Derived* dp = static_cast<Derived*>(bp); // 编译没问题,但你要确保 bp 真的是 Derived*
👉 若运行时类型不确定,建议使用 dynamic_cast
(带运行时类型检查)。
3. void* 与其他类型指针互转(不推荐频繁用)
void* p = malloc(100);
int* ip = static_cast<int*>(p);
在 C 中这是合法的直接转换,但在 C++ 中推荐用 static_cast
显式说明。
4. 枚举类型与整型转换
enum Color { RED = 1, GREEN = 2 };
int x = static_cast<int>(GREEN); // → 2
Color c = static_cast<Color>(1); // → GREEN
5. 删除 const 属性(不可以!)
const int x = 42;
// int* p = static_cast<int*>(&x); // ❌ 错误:不能通过 static_cast 去除 const
// 正确方式:
int* p = const_cast<int*>(&x);
static_cast
不能去掉const
/volatile
修饰符。要用const_cast
。
🚫 static_cast 不适用的场景
- 去除
const
、volatile
→ 用const_cast
- 多态下不确定的指针类型转换 → 用
dynamic_cast
- 非相关类之间的指针强转 → 用
reinterpret_cast
(但不安全)
✅ 总结 static_cast 特点
特性 | 说明 |
---|---|
类型检查 | 编译期检查类型安全 |
语法安全 | 编译器能拒绝不合法转换 |
不能去 const | 改变类型属性需 const_cast |
推荐用途 | 基本类型转换、继承体系向上转换、非 polymorphic 向下转换 |
是否需要几个 static_cast
在实际项目代码中的用例演示?比如网络数据解析、对象池、GUI 转换等?我可以给你做实战演示。
发表回复