rtti例子

版权声明: https://blog.csdn.net/dashoumeixi/article/details/82972261

关于dynamic_cast 的使用:

class GrandFather
{
private:
    int hold;
public:
    GrandFather(int h = 0)    :hold(h){}
    virtual void speak() const { cout << "GrandFather\'s speaking" << endl;}
    virtual int  value() const { return hold;}
};
class Father: public GrandFather
{
  public:
    Father(int h = 0): GrandFather(h){}
    virtual void speak() const {cout << "Father\' s speaking " << endl;}
    virtual void say() const {cout << "Father\'s value:" << value() << endl;}
};
class Child : public Father
{
private:
    char ch;
public:
    Child(int h = 0 , char c = 'A'):Father(h),ch(c){}
    virtual void speak() const { cout << "child\'s speaking" << endl;}
    virtual void say() const {cout << "child \' value:" << value() << "," << ch<< endl;}
};

//以上3个普通的类

//随机获取一个对象
GrandFather * get_one()
{
    GrandFather * p = 0;
    switch(std::rand() % 3)
    {
    case 0: p = new GrandFather(std::rand() % 10);break;
    case 1: p = new Father(std::rand() % 10); break;
    case 2: p = new Child(std::rand() % 10, 'A' + std::rand() % 26);break;
    }
    return p;
}


int main(int argc, char ** argvs)
{
    std::srand(std::time(0));
    GrandFather * gf = 0;
    Father * f = 0;
    for ( int i = 0; i < 10; ++i)
    {
        gf = get_one();
        gf->speak();
        if(f  = dynamic_cast<Father*>(gf)) //安全的类型转换;
            f->say();
        if(typeid(GrandFather) == typeid(*gf))  //也可以这样来判断类型 ;
            std::cout << "\t\t hey , old man" << std::endl;
    }
return 0;
}

猜你喜欢

转载自blog.csdn.net/dashoumeixi/article/details/82972261