C++中查看某变量的类型 typeid().name()

本文详细解析了C++中使用typeid获取类型的内部机制,在Linux与Windows平台下的表现差异,以及如何利用c++filt工具进行类型名的解码,使输出更易于阅读。通过实例展示了不同类型变量的typeid应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 包含头文件

#include <typeinfo>

2. 返回的数据

Linux-g++ 下直接使用typeid(i).name()的结果如下(不便阅读)int i = 0;
	cout << "i's type is: " << typeid(i).name() << endl;//i's type is: i
	
这是因为,Linux的gcc/g++编译器,只输出类型名的第一个字符
		bool:                     b
		 
		char:                     c
		signed char:              a
		unsigned char:            h
		 
		(signed) short (int):     s
		unsigned short (int):     t
		 
		(signed) (int):           i
		unsigned (int):           j
		 
		(signed) long (int):      l
		unsigned long (int):      m
		 
		(signed) long long (int): x
		unsigned long long (int): y
		 
		float:                    f
		double:                   d
		long double:              e

Linux下输出完整的名字需要:
	./execute | c++filt -t

c++filt -t 对结果进行过滤和解码
Windows下只需要:
	int i = 0;
	cout << "i's type is: " << typeid(i).name() << endl;//i's type is: int

3. Test

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

void testP63_decltype()
{
    int i = 42;
    int *p = &i;
    int &r = i;
    //不使用c++filt -t过滤结果的话
    cout << "i's type is: " << typeid(i).name() << endl;//i's type is: i
    cout << "p's type is: " << typeid(p).name() << endl;//p's type is: Pi
    cout << "r's type is: " << typeid(r).name() << endl;//r's type is: i
    //使用c++filt -t过滤结果的话
    //int'short type is: int
	//p'short type is: int*
	//r'short type is: int
}
int main()
{
    testP63_decltype();
    return 0;
}

4. 扩展 c++filt

man c++filt
点击看大图(清楚)
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值