C++如何判断变量类型

本文介绍了C++中如何使用运行时类型信息(RTTI)的typeid操作符来判断变量的类型,并展示了相关代码示例。通过打印typeid的结果并参照类型对照表,可以解读出变量的实际类型。此外,还提供了类型对照表,帮助理解各种内置类型的表示方式。

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

C++如何判断变量类型

使用 typeid 判断其类型:(需要在编译语言选项中选择 RTTI 编译选项),例子:【引用自这里】,详情可以看这里

#include <iostream >
#include <typeinfo.h>
using namespace std;
int main()
{
	char *p=NULL;
	char str[]="hello world";
	cout<<typeid(p).name()<<endl;
	cout<<typeid(str).name()<<endl;
	return 0;
}

打印出的类型并不是可以直接读懂的,可以参考下面的类型对照表【参考自这里】解读。

  <builtin-type> ::= v	# void
		 						::= w	# wchar_t
		 						::= b	# bool
		 						::= c	# char
		 						::= a	# signed char
		 						::= h	# unsigned char
		 						::= s	# short
		 						::= t	# unsigned short
		 						::= i	# int
		 						::= j	# unsigned int
		 						::= l	# long
		 						::= m	# unsigned long
		 						::= x	# long long, __int64
		 						::= y	# unsigned long long, __int64
		 						::= n	# __int128
		 						::= o	# unsigned __int128
		 						::= f	# float
		 						::= d	# double
		 						::= e	# long double, __float80
		 						::= g	# __float128
		 						::= z	# ellipsis
                 				::= Dd # IEEE 754r decimal floating point (64 bits)
                 				::= De # IEEE 754r decimal floating point (128 bits)
                 				::= Df # IEEE 754r decimal floating point (32 bits)
                 				::= Dh # IEEE 754r half-precision floating point (16 bits)
                 				::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits)
                 				::= DB <number> _        # C23 signed _BitInt(N)
                 				::= DB <instantiation-dependent expression> _ # C23 signed _BitInt(N)
                 				::= DU <number> _        # C23 unsigned _BitInt(N)
                 				::= DU <instantiation-dependent expression> _ # C23 unsigned _BitInt(N)
                 				::= Di # char32_t
                 				::= Ds # char16_t
                 				::= Du # char8_t
                 				::= Da # auto
                 				::= Dc # decltype(auto)
                 				::= Dn # std::nullptr_t (i.e., decltype(nullptr))
		 						::= u <source-name> [<template-args>] # vendor extended type
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值