include

include

using namespace std;

class Base{

public:
    virtual ~Base(){

    }

};

class Derived:public Base{

};

int main(){

Base b;
Derived d;
Derived* pd;
pd = reinterpret_cast<Derived*>(&b);    //成功,但不知知道是否安全
if(!pd)
    cout << "unsafe 1" << endl;   //不会执行

pd = dynamic_cast<Derived*>(&b);    //不安全的转换,返回NULL
if(!pd)
    cout << "unsafe 2" << endl; //会执行

Base *pb = &d;
pd = dynamic_cast<Derived*>(pb);    //安全的转换,基类转派生类
if(!pd)
    cout << "unsafe 3" << endl; //不会执行  

return 0;





}

Last modification:May 5th, 2020 at 12:02 pm
Compared with money, your comment could inspire me more.
相较于钱财,你的留言更能激发我创作的灵感