首页 > 代码库 > typeid()的用法

typeid()的用法

#include "Command.h"
#include <iostream>
#include <cstdlib>

//基类A
class A
{
public:
	//虚函数
	virtual A* GetClass()
	{
		return this;
	}
};

//继承于类A的子类AA
class AA:public A
{
public:
	AA* GetClass()
	{
		return this;
	}
};

//继承于类A的子类AAA
class AAA:public A
{
public:
	AAA* GetClass()
	{
		return this;
	}
};

//用来判断类类型的函数
void check(A* a)
{
	if(typeid(*(a->GetClass()))==typeid(A))
		std::cout<<"A"<<std::endl;
	else if(typeid(*(a->GetClass()))==typeid(AA))
		std::cout<<"AA"<<std::endl;
	else if(typeid(*(a->GetClass()))==typeid(AAA))
		std::cout<<"AAA"<<std::endl;
	else
		std::cout<<"else"<<std::endl;
}

void main()
{
	A* a=new A();
	A* aa=new AA();
	A* aaa=new AAA();

	std::cout<<"用typeid(class)判断类的类型:"<<std::endl;
	check(a);
	check(aa);
	check(aaa);

	std::cout<<std::endl<<"用typeid(class).name()显示类类型:"<<std::endl<<typeid(a).name()<<"  "<<typeid(AA).name()<<"  "<<typeid(AAA).name()<<std::endl;

	delete a,aa,aaa;
	system("pause");
}

typeid()的用法