c++关键字typeid

2021-01-15  本文已影响0人  拉普拉斯妖kk
操作 说明
t1 == t2 如果两个对象t1和t2类型相同,则返回true;否则返回false
t1 != t2 如果两个对象t1和t2类型不同,则返回true;否则返回false
t.name() 返回类型的C-style字符串。由编译器决定,不一定就是真实的类型名
t1.before(t2) 判断t1是否位于t2的前面。类型排列顺序与编译器相关,基类不一定位于派生类的前面。
#include<iostream>  
#include <typeinfo>  
using namespace std;  

class Base{};
class Derived:public Base{};
void func1();
int func2(int n);

int main()  
{  
    int a = 10;
    int* b = &a;
    float c;
    double d;

    cout << typeid(a).name() << endl;
    cout << typeid(b).name() << endl;
    cout << typeid(c).name() << endl;
    cout << typeid(d).name() << endl;
    cout << typeid(Base).name() << endl;
    cout << typeid(Derived).name() << endl;
    cout << typeid(func1).name() << endl;
    cout << typeid(func2).name() << endl;
}  
i
Pi
f
d
4Base
7Derived
FvvE
FiiE
#include<iostream>  
#include <typeinfo>  
using namespace std; 

class Base{};
class Drived: public Base{};

int main()
{
    Base* pb;
    Drived d;
    pb = &d;

    if(strcmp(typeid(*pb).name(), typeid(Base).name()) == 0)
    {
        cout << "this is Base" << endl;
    }
    else if(strcmp(typeid(*pb).name(), typeid(Drived).name()) == 0)
    {
        cout << "this is Drived" << endl;
    }
    
    if(strcmp(typeid(d).name(), typeid(Base).name()) == 0)
    {
        cout << "this is Base" << endl;
    }
    else if(strcmp(typeid(d).name(), typeid(Drived).name()) == 0)
    {
        cout << "this is Drived" << endl;
    }
}
this is Base
this is Drived
上一篇 下一篇

猜你喜欢

热点阅读