dynamic_cast和static_cast

dynamic_cast:
必须是指针或引用
要有虚函数
有继承关系(否则返回空指针)

static_cast:
基类转派生类不能为对象
没有继承关系的转换会失败

#include 
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(d1);//派生类对象转化为基类对象
    //d1 = static_cast(b1);

    B* pb1 = new B();
    D* pd1 = static_cast(pb1); //基类指针转化为派生类指针
    if (pd1) cout << "static_cast, B* --> D* : OK" << endl;

    pd1 = dynamic_cast(pb1); //转换失败,
    //dynamic_cast只有当基类指针指向派生类对象时才可以转换,这种机制确保了转换的安全性
    if (!pd1) cout << "dynamic_cast, B* --> D*: FAILED" << endl;

    D* pd2 = new D();
    B* pb2 = static_cast(pd2); //派生类指针转化为基类指针
    if (pb2) cout << "static_cast, D* --> B*: OK" << endl;
    pb2 = dynamic_cast(pd2);  //派生类指针转化为基类指针
    if (pb2) cout << "dynamic_cast, D* --> B* : OK" << endl;

    E* pe = dynamic_cast(pb1);  //没有继承关系返回空指针
    if (pe == NULL) cout << "NULL pointer" << endl;
    //pe = static_cast(pb1); //B* -> E*没有继承关系

    return 0;
}

你可能感兴趣的:(c++)