RTTI是”Runtime Type Information”的缩写,意思是运行时类型信息,它提供了运行时确定对象类型的方法。
在C++当中,RTTI的使用,主要是typeinfo头文件当中的typeid,它的使用方法如下:
#include <iostream>
#include <typeinfo>
using namespace std;
class A
{
public:
void Print() { cout<<"This is class A."<<endl; }
};
class B : public A
{
public:
void Print() { cout<<"This is class B."<<endl; }
};
struct C
{
void Print() { cout<<"This is struct C."<<endl; }
};
int main()
{
A *pA1 = new A();
A a2;
cout<<typeid(pA1).name()<<endl; // class A *
cout<<typeid(a2).name()<<endl; // class A
B *pB1 = new B();
cout<<typeid(pB1).name()<<endl; // class B *
C *pC1 = new C();
C c2;
cout<<typeid(pC1).name()<<endl; // struct C *
cout<<typeid(c2).name()<<endl; // struct C
return 0;
}
其中,typeid(object)返回的是一个type_info类,该类保存了object对象的一些元数据。type_info的结构如下:
class
type_info
{
public:
virtual ~type_info();
bool operator==(const type_info& _Rhs) const; // 用于比较两个对象的类型是否相等
bool operator!=(const type_info& _Rhs) const; // 用于比较两个对象的类型是否不相等
bool before(const type_info& _Rhs) const;
// 返回对象的类型名字,这个函数用的很多
const char* name(__type_info_node* __ptype_info_node = &__type_info_root_node) const;
const char* raw_name() const;
private:
void *_M_data;
char _M_d_name[1];
type_info(const type_info& _Rhs);
type_info& operator=(const type_info& _Rhs);
static const char * _Name_base(const type_info *,__type_info_node* __ptype_info_node);
static void _Type_info_dtor(type_info *);
};
在Java当中,RTTI的形式主要有三种:
(1)传统的类型转换(即常用的“Classb b =(Classb )a”,其中b为a的子类);
(2)代表对象的类型的Class对象。通过查询Class对象可以获取运行时所需的信息;
(3)关键字instanceof