c++ typeid().name()獲取變量類型

簡介

typeid是C++的關鍵字之一,等同於sizeof這類的操作符。

typeid操作符的返回結果是名爲type_info的標準庫類型的對象的引用, 故需要包含頭文件:#include <typeinfo>.

typeid(a).name()可以返回變量a的類型;

舉例

#include <iostream>
#include <typeinfo> 

using namespace std;
int main()
{
	bool a;
    char b;
    short c;
    int d;
    long e;
    float f;
    double g;
    long long h;
    cout<<typeid(a).name()<<endl;
    cout<<typeid(b).name()<<endl;
    cout<<typeid(c).name()<<endl;
    cout<<typeid(d).name()<<endl;
    cout<<typeid(e).name()<<endl;
    cout<<typeid(f).name()<<endl;
    cout<<typeid(g).name()<<endl;
    cout<<typeid(h).name()<<endl;
    return 0;
}

輸出結果:

b
c
s
i
l
f
d
x

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章