static_cast是一种用于类型转换的C++运算符。它可以将一个类型的值转换为另一个类型,但只适用于具有转换关系的类型。以下是static_cast的常见用法:
int num = 10; double numDouble = static_cast<double>(num); double numDouble = 10.5; int numInt = static_cast<int>(numDouble); int num = 10; int* numPtr = # void* voidPtr = static_cast<void*>(numPtr); int num = 10; int* numPtr = # double* doublePtr = static_cast<double*>(numPtr); class Base { public: virtual void func() {} }; class Derived : public Base { public: void func() override {} }; Base* basePtr = new Derived(); Derived* derivedPtr = static_cast<Derived*>(basePtr); 需要注意的是,使用static_cast进行类型转换时,编译器不会进行运行时类型检查,因此在使用时需要确保转换是安全的。如果转换不安全,则可能会导致未定义的行为。如果不确定转换是否安全,可以使用dynamic_cast进行类型转换,它会在运行时检查类型。