美文网首页
typeid和typeinfo

typeid和typeinfo

作者: arkliu | 来源:发表于2022-10-31 09:08 被阅读0次

    typeid

    运行时获知变量类型名称,返回值为type_info类型,可以使用 typeid(变量).name()

    #include<iostream>
    #include<string>
    #include<typeinfo>
    using namespace std;
    
    class AA{
    
    };
    
    int main() {
        // typeid 用于自定义的数据类型
        AA aa;
        AA *paa = &aa;
        AA &raa = aa;
        cout << "typeid(AA) = " << typeid(AA).name()<<endl;
        cout << "typeid(aa) = " << typeid(aa).name()<<endl;
        cout << "typeid(AA *) = " << typeid(AA *).name()<<endl;
        cout << "typeid(paa) = " << typeid(paa).name()<<endl;
        cout << "typeid(AA &) = " << typeid(AA &).name()<<endl;
        cout << "typeid(raa) = " << typeid(raa).name()<<endl;
    
        // type_info重载了==和!= 运算符,用于对类型进行比较
        if (typeid(AA) == typeid(aa))
        {
            cout << " aa is AA instance "<<endl;
        }
        return 0;
    }
    
    image.png

    相关文章

      网友评论

          本文标题:typeid和typeinfo

          本文链接:https://www.haomeiwen.com/subject/kjinzrtx.html