C++中输出变量类型的方法

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则是一长串字符串。而自己定义的类的对象则是打印出类名。

posted @ 2020-08-26 13:44  凡璞  阅读(5653)  评论(0编辑  收藏  举报
1 2
3 4
5 6