static_cast:用于普通/普通类型转换。这也是负责隐式类型强制的强制转换,也可以显式调用。在将float转换为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:此强制转换用于处理多态。您只需要在转换为派生类时使用它。从基类转换为派生类时,只能在继承中使用它。
#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