static_cast 是 C++ 中的一个类型转换运算符,它用于在编译时进行类型转换。这种转换在编译时就必须是安全的,因此编译器会检查转换是否合法。如果转换不合法,编译器会报错。
static_cast 可以用在多种场景,包括但不限于:
1.非多态类型之间的转换:比如从派生类到基类的转换,或者从基类到派生类的转换(在派生类公开继承基类的情况下)。
class Base {};
class Derived : public Base {};
Derived d;
Base& b = static_cast<Base&>(d); // 派生类到基类的转换
Base b2;
Derived* dp = static_cast<Derived*>(&b2); // 这里会编译失败,因为基类到派生类的转换不是总是安全的
2.基本数据类型之间的转换:比如从 int 到 double,或者从 void* 到其他指针类型。
int i = 42;
double d = static_cast<double>(i); // int 到 double 的转换
void* ptr = ...;
int* intPtr = static_cast<int*>(ptr); // void* 到 int* 的转换
3.执行向上和向下转型:在类继承体系中,向上转型(从派生类到基类)通常是安全的,而向下转型(从基类到派生类)需要确保对象确实是派生类类型的实例。
Base* basePtr = new Derived();
Derived* derivedPtr = static_cast<Derived*>(basePtr); // 向下转型
4.执行 const 或 volatile 的添加或移除:static_cast 可以用来改变一个指针或引用的 const 或 volatile 属性。
const int* constPtr = ...;
int* nonConstPtr = static_cast<int*>(constPtr); // 移除 const 属性
需要注意的是,static_cast 是一种编译时转换,它要求程序员对转换的安全性有明确的了解。如果转换可能导致运行时错误,编译器通常不会阻止这种转换,因此程序员需要格外小心。