C++ 中的 Dynamic_cast 和 static_cast
static_cast:这用于正常的类型转换。这还负责隐式类型强制转换的 cast,还可以显式地调用。您应该在诸如将浮点转换为 int、char 转换为 int 等情况下使用它。这可以转换相关的类型类。如果类型不同,它将生成一些错误。
示例
#include<iostream> using namespace std; class Base {}; class Derived : public Base {}; class MyClass {}; main(){ Derived* d = new Derived; Base* b = static_cast<Base*>(d); // this line will work properly MyClass* x = static_cast<MyClass*>(d); // ERROR will be generated during compilation }
输出
[Error] invalid static_cast from type 'Derived*' to type 'MyClass*'
dynamic_cast:这个 cast 用于处理多态。只有在转换为派生类时才需要使用它。在从基类转换为派生类时,专门用于继承中。
示例
#include<iostream> using namespace std; class MyClass1 { public: virtual void print()const { cout << "This is from MyClass1\n"; } }; class MyClass2 { public: virtual void print()const { cout << "This is from MyClass2\n"; } }; class MyClass3: public MyClass1, public MyClass2 { public: void print()const { cout << "This is from MyClass3\n"; } }; int main(){ MyClass1* a = new MyClass1; MyClass2* b = new MyClass2; MyClass3* c = new MyClass3; a -> print(); b -> print(); c -> print(); b = dynamic_cast< MyClass2*>(a); //This cast will be failed if (b) b->print(); else cout << "no MyClass2\n"; a = c; a -> print(); //Printing from MyClass3 b = dynamic_cast< MyClass2*>(a); //Successfully casting is done if (b) b -> print(); else cout << "no MyClass2\n"; }
输出
This is from MyClass1 This is from MyClass2 This is from MyClass3 no MyClass2 This is from MyClass3 This is from MyClass3
广告