dynamic_cast:
必须是指针或引用
要有虚函数
有继承关系(否则返回空指针)
static_cast:
基类转派生类不能为对象
没有继承关系的转换会失败
#include <iostream>
using namespace std;
class B {public : virtual void f() {} };//dynamic要求有虚函数
class D : public B {};
class E{};
int main()
{
D d1;
B b1;
b1 = static_cast<B>(d1);//派生类对象转化为基类对象
//d1 = static_cast<D>(b1);
B* pb1 = new B();
D* pd1 = static_cast<D*>(pb1); //基类指针转化为派生类指针
if (pd1) cout << "static_cast, B* --> D* : OK" << endl;
pd1 = dynamic_cast<D*>(pb1); //转换失败,
//dynamic_cast只有当基类指针指向派生类对象时才可以转换,这种机制确保了转换的安全性
if (!pd1) cout << "dynamic_cast, B* --> D*: FAILED" << endl;
D* pd2 = new D();
B* pb2 = static_cast<B*>(pd2); //派生类指针转化为基类指针
if (pb2) cout << "static_cast, D* --> B*: OK" << endl;
pb2 = dynamic_cast<B*>(pd2); //派生类指针转化为基类指针
if (pb2) cout << "dynamic_cast, D* --> B* : OK" << endl;
E* pe = dynamic_cast<E*>(pb1); //没有继承关系返回空指针
if (pe == NULL) cout << "NULL pointer" << endl;
//pe = static_cast<E*>(pb1); //B* -> E*没有继承关系
return 0;
}