云守护的专栏

专注于移动安全、游戏安全、逆向安全 ;------------------------- 邮箱:1309521515@qq.com...

c++ RTTI例子
#include <string>
#include <iostream>
#include <typeinfo>
#include <stdio.h>
using namespace std;

class Base
{
public:
    Base(){
        strcpy(name,"Base");
    }
    virtual void display()
    {
        cout<<"Display Base."<<endl;
    }
protected:
    char name[64];
};

class Child1:public Base
{
public:
    Child1()
    {
        strcpy(name,"Child1");
    }
    void display()
    {
        cout<<"Display Child1."<<endl;
    }
};

class Child2:public Base
{
public:
    Child2()
    {
        strcpy(name,"Child2");
    }
    void display()
    {
        cout<<"Display Child2."<<endl;
    }
};

void Process(Base *type)
{
    if( (typeid(Child1)) == (typeid(*type)) )
    {
        //((Child1*)type)->display();
        Child1* ch=dynamic_cast<Child1*>(type);
        ch->display();
    }
    else if( (typeid(Child2)) == (typeid(*type)) )
    {
        //((Child2*)type)->display();
       Child2* ch=dynamic_cast<Child2*>(type);
       ch->display();
    }
    else
    {
        cout<<"Unknow type!"<<endl;
    }
}

int main(void)
{
    Base *pT1 = new Child1();
    Base *pT2 = new Child2();
    Process(pT1);
    Process(pT2);

    printf("raw_name=%s name=%s hash_code=%d\n",typeid(pT1).raw_name(),typeid(pT1).name(),typeid(pT1).hash_code());
    printf("OK\n");
    return 0;
}



阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/earbao/article/details/52347509
个人分类: c/c++
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

c++ RTTI例子

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭