dynamic_cast的用处

#include <iostream>
#include <vector>
#include <string>
#include <exception>
#include <stdexcept>
#define TEST_THIS
using namespace std;

class Parent{
public :
    virtual void say(){cout<<"parent"<<endl;}
};
class Son:public Parent{

public :
    virtual void say(){cout<<"son"<<endl;}
};

class Son1{
    public :
    virtual void say(){cout<<"son1"<<endl;}
};

int main()
{
    Parent *p=new Son;
    Son1 *ps= (Son1 *)p;//这样转换居然也能成功,ps-say()调用,输出son
    //Son1 *ps= dynamic_cast<Son1 *>(p);//转换不成功,ps为NULL,安全
    //Son *ps= dynamic_cast<Son *>(p);//转换成功
    cout<<ps<<endl;

    ps->say();
    delete p;


    #ifndef TEST_THIS
    try{
        int i=0;
        int a=10/i;
        cout<<a<<endl;
    }catch(runtime_error ex){
        cout<<ex.what()<<endl;
    }
    #endif
    vector<string> svec(5);
    svec[4]="abc";

    int *pi=new int;
    cout<<*pi<<endl;

    int *pi2=new int();
    cout<<*pi2<<endl;

    cout<<"done"<<endl;

    delete pi;
    delete pi2;
    cout<<pi<<","<<pi2<<endl;

    return 0;
}
posted @ 2011-05-23 17:48  庚武  Views(251)  Comments(0Edit  收藏  举报