关于c++:c关键字typeid

5次阅读

共计 1604 个字符,预计需要花费 5 分钟才能阅读完成。

  • 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;}  
  • Mac 下应用 clang++ 编译运行后果如下:
i
Pi
f
d
4Base
7Derived
FvvE
FiiE
  • 不像 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;}
}
  • Mac 下应用 clang++ 编译运行后果如下:
this is Base
this is Drived
  • 从运行后果中能够看出,即应用基类指针指向派生类,但应用 typeid 判断的基类指针类型仍然是基类指针。因而咱们不能用 typeid 来判断基类指针理论指向的是否是某个派生类。
正文完
 0