在类转换中,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<Derived*>(basePtr);
derivedPtr->func(); // 输出 "Derived function"
delete basePtr;
return 0;
}
enum class Color {
Red,
Blue,
Green
};
int main() {
int colorValue = 1;
Color color = static_cast<Color>(colorValue);
return 0;
}
class MyClass {
public:
void func() {
cout << "Hello, World!" << endl;
}
};
int main() {
MyClass* myClassPtr = new MyClass();
void* voidPtr = static_cast<void*>(myClassPtr);
MyClass* newMyClassPtr = static_cast<MyClass*>(voidPtr);
newMyClassPtr->func(); // 输出 "Hello, World!"
delete myClassPtr;
return 0;
}