- typeid是c++的一个关键字,typeid操作符的返回后果是规范库类型type_info对象的援用。
- 然而,C++规范并没有明确定义type_info,其具体实现依赖于各个编译器。规范只规定了typeid操作符必须实现如下四种操作:
操作 | 阐明 |
---|
t1 == t2 | 如果两个对象t1和t2类型雷同,则返回true;否则返回false |
t1 != t2 | 如果两个对象t1和t2类型不同,则返回true;否则返回false |
t.name() | 返回类型的C-style字符串。由编译器决定,不肯定就是实在的类型名 |
t1.before(t2) | 判断t1是否位于t2的后面。类型排列程序与编译器相干,基类不肯定位于派生类的后面。 |
- type_info的成员函数name返回类型的C-style字符串,但这个返回的类型名与程序中应用的相应类型名不肯定统一,其返回值的实现由编译器决定,规范只要求每个类型返回的字符串是惟一的。
- 和sizeof操作符相似,typeid的操作对象既能够是数据类型,也能够是表达式。
- 应用typeid判断各种类型示例代码如下:
#include<iostream> #include <typeinfo> using namespace std; class Base{};class Derived:public Base{};void func1();int func2(int n);int main() { int a = 10; int* b = &a; float c; double d; cout << typeid(a).name() << endl; cout << typeid(b).name() << endl; cout << typeid(c).name() << endl; cout << typeid(d).name() << endl; cout << typeid(Base).name() << endl; cout << typeid(Derived).name() << endl; cout << typeid(func1).name() << endl; cout << typeid(func2).name() << endl;}
iPifd4Base7DerivedFvvEFiiE
- 不像Java、C#等动静语言,C++运行时能获取到的类型信息十分无限,规范也定义的很含糊,如同“鸡肋”个别。在理论工作中,咱们个别只应用type_info的“==”运算符来判断两个类型是否雷同。
- 再来看看上面的示例代码:
#include<iostream> #include <typeinfo> using namespace std; class Base{};class Drived: public Base{};int main(){ Base* pb; Drived d; pb = &d; if(strcmp(typeid(*pb).name(), typeid(Base).name()) == 0) { cout << "this is Base" << endl; } else if(strcmp(typeid(*pb).name(), typeid(Drived).name()) == 0) { cout << "this is Drived" << endl; } if(strcmp(typeid(d).name(), typeid(Base).name()) == 0) { cout << "this is Base" << endl; } else if(strcmp(typeid(d).name(), typeid(Drived).name()) == 0) { cout << "this is Drived" << endl; }}
this is Basethis is Drived
- 从运行后果中能够看出,即应用基类指针指向派生类,但应用typeid判断的基类指针类型仍然是基类指针。因而咱们不能用typeid来判断基类指针理论指向的是否是某个派生类。