C++中的typeid关键字

typeid是C++中RTTI(Run-TimeType Information, 运行时类型识别)机制的组成部分,其目的是根据传入已有的参数,来判断参数的数据类型。

对于基本数据类型的用法与运行结果(g++ 6.3.0):

#include <iostream>
#include <typeinfo>

using namespace std;

int main()
{
    int a = 0;
    float b = 0;
    double c = 0;
    char d = 0;

    cout << typeid(int).name()<< endl;
    cout << typeid(a).name()<< endl;
    cout << typeid(float).name()<< endl;
    cout << typeid(b).name()<< endl;
    cout << typeid(double).name()<< endl;
    cout << typeid(c).name()<< endl;
    cout << typeid(char).name()<< endl;
    cout << typeid(d).name()<< endl;
    cout << typeid(&d).name()<< endl;
}

运行结果:

leo@leo-X550JD:~$ ./a.out 
i
i
f
f
d
d
c
c
Pc

对于类中的用法和运行结果(g++ 6.3.0):

#include <iostream>
#include <typeinfo>

using namespace std;

//基类
class Base
{
  public:
    Base()
    {
        //Base
    }
    ~Base(){};
};

//派生类
class Person : public Base
{
  public:
    Person()
    {
        //Person
    }
    ~Person(){};
};

int main()
{
    Base a;
    Person b;

    Base *c = new Person;

    cout << typeid(Base).name() << endl;
    cout << typeid(a).name() << endl
         << endl;

    cout << typeid(Person).name() << endl;
    cout << typeid(b).name() << endl
         << endl;

    cout << typeid(Base*).name() << endl;     
    cout << typeid(c).name() << endl;
    cout << typeid(*c).name() << endl
         << endl;
}

运行结果:

4Base
4Base

6Person
6Person

P4Base
P4Base
4Base

其中,P开头的是指针类型。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值