C++ type_info简介

    C++提供了一个type_info类来获取对象类型信息,具有如下特点:

    (1)这个类的构造函数是private的,因此用户不能直接构造这样的对象,只能通过typeid()函数来获取这个对象.

    (2)这个类对外提供了name(),operator==()等方法供用户使用.

    (3)typeid()可以对基本的数据类型和对象进行操作,这种情况下,是在编译期静态决定的.如:

                typeid(int);

                int a; typeid(a);

    (4)type_info也可以对类类型和类对象进行操作,分两种情况:如果是声明了虚函数的类对象引用,则typeid()返回的是实际对象的类型信息,在运行时动态决定的;反之(没有定义虚函数,或者即使定义了虚函数但传入的是对象指针),则typeid()返回的是入参声明类型信息,在编译时静态决定的.

    示例代码如下:

    (1)基本数据类型示例:

#include <iostream>
#include <typeinfo>

using namespace std;

int main(void) {
    // Basic data type
    char a = 'a';
    short b = 10;
    int c = 99;
    long d = 20;
    float e = 2.3;
    double f = 4.8;

    cout << typeid(char).name() << endl;
    cout << typeid(a).name() << endl;
    cout << typeid(short).name() << endl;
    cout << typeid(b).name() << endl;
    cout << typeid(int).name() << endl;
    cout << typeid(c).name() << endl;
    cout << typeid(long).name() << endl;
    cout << typeid(d).name() << endl;
    cout << typeid(float).name() << endl;
    cout << typeid(e).name() << endl;
    cout << typeid(double).name() << endl;
    cout << typeid(f).name() << endl;

    if (typeid(f) == typeid(double)) {
        cout << "type is equal" << endl;
    } else {
        cout << "type is not equal" << endl;
    }
   
    return 0;
}

运行结果:

c
c
s
s
i
i
l
l
f
f
d
d
type is equal

    (2)无虚函数示例代码:

#include <iostream>
#include <typeinfo>

using namespace std;

class Base {
public:
    void func() {cout << "Base::func()" << endl;};
};

class Derived: public Base {
};

int main(void) {
    Derived derived;
    Base base, *pbase, &rbase = derived;
    pbase = &derived;

    cout << typeid(base).name() << endl;   
    cout << typeid(derived).name() << endl;
    cout << typeid(pbase).name() << endl;
    cout << typeid(rbase).name() << endl;
    
    return 0;
}

    运行结果:

4Base
7Derived
P4Base
4Base

    (3)有虚函数示例代码:

#include <iostream>
#include <typeinfo>

using namespace std;

class Base {
public:
    virtual void func() {cout << "Base::func()" << endl;};
};

class Derived: public Base {
};

int main(void) {
    Derived derived;
    Base base, *pbase, &rbase = derived;
    pbase = &derived;

    cout << typeid(base).name() << endl;   
    cout << typeid(derived).name() << endl;
    cout << typeid(pbase).name() << endl;
    cout << typeid(rbase).name() << endl;
  
    return 0;
}

    运行结果:

4Base
7Derived
P4Base
7Derived

 

转载于:https://my.oschina.net/yepanl/blog/1596740

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值