**核心功能**
1. **基本类型转换**
用于数值类型(如 `int`、`double`)、指针类型、引用类型之间的转换。
```cpp
double d = 3.14;
int i = static_cast<int>(d); // 截断小数部分,i = 3
```
2. **父子类指针/引用转换**
- **向上转换**(子类 → 父类):安全,隐式转换也可完成。
- **向下转换**(父类 → 子类):需程序员确保类型安全,否则可能导致未定义行为。
```cpp
class Base {};
class Derived : public Base {};
Derived d;
Base* pb = &d; // 隐式向上转换
Derived* pd = static_cast<Derived*>(pb); // 向下转换(需确保 pb 指向 Derived 对象)
```
3. **显式调用用户定义的转换函数**
```cpp
class A {
public:
operator int() const { return 42; }
};
A a;
int x = static_cast<int>(a); // 调用 A::operator int()
```
4. **枚举与整数的互转**
```cpp
enum Color { Red, Green, Blue };
Color c = Red;
int value = static_cast<int>(c); // 转换为整数(0)
```
5. **void* 与其他指针类型的转换**
```cpp
int num = 42;
void* vp = #
int* ip = static_cast<int*>(vp); // 从 void* 转回 int*
```
**与其他转换操作符的对比**
| 操作符 | 主要用途 | 安全性 |
|----------------|-----------------------------------|------------------------|
| `static_cast` | 基本类型转换、父子类转换 | 编译时检查,需手动保证 |
| `dynamic_cast` | 运行时类型安全的多态类型转换 | 最安全(但有性能开销) |
| `const_cast` | 去除 `const`/`volatile` 限定符 | 可能导致未定义行为 |
| `reinterpret_cast` | 底层二进制位重新解释 | 最不安全 |
**使用注意事项**
1. **不检查运行时类型**
对于向下转换(父类 → 子类),若实际对象类型不匹配,`static_cast` 不会报错,但访问子类特有成员会导致未定义行为。此时应优先使用 `dynamic_cast`(需基类包含虚函数)。
2. **不可用于去除 `const` 限定**
```cpp
const int x = 10;
int* px = static_cast<int*>(&x); // 错误!需用 const_cast
```
3. **避免危险转换**
例如将函数指针转换为数据指针,或跨继承层级的转换(如兄弟类之间),这类操作应使用 `reinterpret_cast`(但极不安全)。
**示例代码**
cpp
#include <iostream>
class Shape {
public:
virtual ~Shape() = default; // 虚析构函数,使 dynamic_cast 可用
};
class Circle : public Shape {};
class Square : public Shape {};
int main() {
// 1. 基本类型转换
double pi = 3.14159;
int truncated = static_cast<int>(pi); // 3
// 2. 向上转换(安全)
Circle circle;
Shape* shapePtr = &circle; // 隐式转换
// 3. 向下转换(需谨慎)
Shape* anotherShape = new Square();
Circle* circlePtr = static_cast<Circle*>(anotherShape); // 危险!anotherShape 实际是 Square
// circlePtr->... 访问 Circle 成员会导致未定义行为
// 4. 安全的向下转换应使用 dynamic_cast
if (Circle* safeCircle = dynamic_cast<Circle*>(anotherShape)) {
// 进入此分支需 anotherShape 实际指向 Circle
} else {
std::cout << "转换失败,anotherShape 不是 Circle" << std::endl;
}
delete anotherShape;
return 0;
}
**总结**
- **适用场景**:明确知道类型关系的转换(如枚举与整数、父子类转换)。
- **安全建议**:避免使用 `static_cast` 进行跨继承层级或不同类型指针的转换,此类操作应使用 `reinterpret_cast` 并充分理解风险。