C++中輸出變數型別的方法
阿新 • • 發佈:2020-08-26
C++中輸出變數型別的方法
在c++中輸出變數或者資料型別,使用typeid().name()的方法。如下例子:
#include <iostream> #include <string> using namespace std; class C{}; int main(int argc, char const *argv[]) { char c = 'a'; int i = 7; int *ii = &i; long l = 5; float f = 3.14; double d = 3.1415; string str = "HelloWorld"; C cl = C(); cout << typeid(c).name() << endl; cout << typeid(i).name() << endl; cout << typeid(ii).name() << endl; cout << typeid(l).name() << endl; cout << typeid(f).name() << endl; cout << typeid(d).name() << endl; cout << typeid(str).name() << endl; cout << typeid(str[1]).name() << endl; cout << typeid(cl).name() << endl; return 0; }
輸出結果為:
c
i
Pi
l
f
d
NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
c
1C
這個結果並不像別的文章展示的char、int、long等等的這樣將型別全稱打出。簡單型別只打印出開頭首字母,而指標型別顯示的是Pi即Pointer的縮寫,string則是一長串字串。而自己定義的類的物件則是打印出類名。