C++中的中的RTTI机制详解机制详解
前言前言
RTTI是”Runtime Type Information”的缩写,意思是运行时类型信息,它提供了运行时确定对象类型的方法。RTTI并不是什么
新的东西,很早就有了这个技术,但是,在实际应用中使用的比较少而已。而我这里就是对RTTI进行总结,今天我没有用
到,并不代表这个东西没用。学无止境,先从typeid函数开始讲起。
typeid函数函数
typeid的主要作用就是让用户知道当前的变量是什么类型的,比如以下代码:
代码如下:
#include <iostream>
#include <typeinfo>
using namespace std;
int main()
{
short s = 2;
unsigned ui = 10;
int i = 10;
char ch = ‘a’;
wchar_t wch = L’b’;
float f = 1.0f;
double d = 2;
cout<<typeid(s).name()<<endl; // short
cout<<typeid(ui).name()<<endl; // unsigned int
cout<<typeid(i).name()<<endl; // int
cout<<typeid(ch).name()<<endl; // char
cout<<typeid(wch).name()<<endl; // wchar_t
cout<<typeid(f).name()<<endl; // float
cout<<typeid(d).name()<<endl; // double
return 0;
}
对于C++支持的内建类型,typeid能完全支持,我们通过调用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
评论0
最新资源