C++ 类型转换运算符包括静态类型转换(static_cast)、动态类型转换(dynamic_cast)、常量类型转换(const_cast)和重解释类型转换(reinterpret_cast)。在处理复杂情况时,这些类型转换运算符可以帮助我们在不同类型之间进行安全的转换。
int num = 42; double d = static_cast<double>(num); // 将 int 类型转换为 double 类型
class Base { virtual ~Base() {} }; class Derived : public Base {}; Base* b = new Derived(); Derived* d = dynamic_cast<Derived*>(b); // 将 Base 类型指针转换为 Derived 类型指针
const int a = 42; int* p = const_cast<int*>(&a); // 移除 const 修饰符,但这样做可能导致未定义行为
int a = 42; char* c = reinterpret_cast<char*>(&a); // 将 int 类型转换为 char 类型
在处理复杂情况时,应根据实际需求选择合适的类型转换运算符。同时,要注意避免使用不安全的转换,如过度使用 reinterpret_cast,以免导致程序出现未定义行为。