在类转换中,static_cast可以用于以下情况:
- 将基类指针或引用转换为派生类指针或引用。这种转换只能在编译器已知源类型和目标类型之间存在继承关系时才能进行。
class Base { public: virtual void func() { cout << "Base function" << endl; } }; class Derived : public Base { public: void func() override { cout << "Derived function" << endl; } }; int main() { Base* basePtr = new Derived(); Derived* derivedPtr = static_cast(basePtr); derivedPtr->func(); // 输出 "Derived function" delete basePtr; return 0; }
- 将整数类型转换为枚举类型。
enum class Color { Red, Blue, Green }; int main() { int colorValue = https://www.yisu.com/ask/1;>(colorValue); return 0; }
- 将指针类型转换为void指针类型。
class MyClass { public: void func() { cout << "Hello, World!" << endl; } }; int main() { MyClass* myClassPtr = new MyClass(); void* voidPtr = static_cast(myClassPtr); MyClass* newMyClassPtr = static_cast (voidPtr); newMyClassPtr->func(); // 输出 "Hello, World!" delete myClassPtr; return 0; }