C++操作符typeid获取对象类型的应用

typeid是一个运算符, 类似于sizeof
typeid定义在头文件typeinfo中,必须包含该头文件
typeid用来返回一个变量/表达式/对象的类型


typeid的深层次理解

    1. 一个表达式的类型分静态类型和动态类型,分别对应编译器和运行时类型决策系统。
        比如: int和char等基本类型属于静态类型,编译器已定下来的。
        而(void*)属于动态类型,得在运行时才能确定下来具体类型是(int*) 还是(char*)等。

    2. typeid可用来返回静态类型,也可用来返回动态类型。

    3. typeid是C++语言本身的特性,由编译器和库函数共同支撑

    4. ypteid真正大用在引入class和继承后,并结合指针和引用后才能显现出来。

演示源码:

// Len_typeid.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <typeinfo>
using namespace std;

struct Student
{
    int nAge;
    int nClass;
    char nName[24];
};

enum GRAD
{
    level_first=0,
    level_second,
    level_third    
};
int main()
{
    signed char a;
    cout << "\na type = " << typeid(a).name() << endl;

    signed char* b;
    b = &a;
    cout << "\nb type = " << typeid(b).name() << endl;

    Student stu = { 25,1,"张小菜" };
    cout << "\nstu type = " << typeid(stu).name() << endl;

    GRAD g = GRAD::level_second;
    cout << "\ng type = " << typeid(g).name() << endl;

    void* p;
    p= &a;
    cout << "\np type = " << typeid(p).name() << endl;

}

执行结果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WendyWJGu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值