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;
}
执行结果: