c++ 中使用typeid

c++ 中使用typeid

在c++中,typeid用于返回指针或引用所指对象的实际类型。
注意:typeid是操作符,不是函数!类似于sizeof一样
使用typeid要包含#include <typeinfo>
使用typeid(value).name()获得类型名称,返回的名称由编译器决定。
name()函数原型代码:

 /** Returns an @e implementation-defined byte string; this is not
     *  portable between compilers!  */
    const char* name() const _GLIBCXX_NOEXCEPT
    { return __name[0] == '*' ? __name + 1 : __name; }

本例子是在g++编译器编译

#include <iostream>
#include <vector>
#include <string>
#include <typeinfo>
using std::vector;
using std::string;
using std::cout;
using std::endl;
class A
{

};
class B:public A
{

};
int main()
{
   char _char='a';
    cout << typeid(_char).name()<<endl;

    int _int=3;
    cout << typeid(_int).name()<<endl;

    float _float;
    cout << typeid(_float).name()<<endl;

    double _double;
    cout << typeid(_double).name()<<endl;

    long long int _longInt;
    cout << typeid(_longInt).name()<<endl;

    int ia[3][4] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };

    auto p=ia;
    cout<< typeid(p).name() <<endl;

    string _string="str";
    cout << typeid(_string).name()<<endl;

    vector<string> vecStr{"hello123","t123123est"};
    cout <<typeid(vecStr).name()<<endl;

    A _a;
    cout << typeid(_a).name()<<endl;

    B _b;
    cout << typeid(_b).name()<<endl;

    A _aa= _b;
    cout << typeid(_aa).name()<<endl;
    return 0;
}

运行结果图:
这里写图片描述


因为我使用的是g++编译器,输出的变量类型很奇怪,如果使用vs2013,结果应该不同,如果要比较两个类型不同,可以typeid(lhs)==typeid(rhs)来比较

猜你喜欢

转载自blog.csdn.net/zqw_yaomin/article/details/81277425