#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;
}
c++ RTTI例子
最新推荐文章于 2021-07-09 08:43:07 发布