C++中获取变量的数据类型,以及对数据类型进行比较(使用hash_code()生成代表此类型的唯一值)

1、变量的数据类型获取,需要包含头文件 typeinfo
2、使用typeid(),包含需要获取数据类型的变量名
3、使用成员函数name(),获取数据类型的名称
4、使用成员函数hash_code(),生成代表此类型的唯一哈希值(C++11)

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

int main()
{
	int a =  1;
	auto a_type = typeid(a).name(); // 获取类型名称
	cout << "a_tpye = " << a_type << endl;

	float b = 2;
	float c = 3;
	auto b_hash_code = typeid(b).hash_code();	// C++ 11中的新特性,返回该类型唯一的哈希值
	auto c_hash_code = typeid(c).hash_code();	

	if (b_hash_code == c_hash_code)
	{
		cout << "b type == c type. hash code = " << b_hash_code << endl;
	}

	return EXIT_SUCCESS;
}

运行结果:

a_tpye = int
b type == c type. hash code = 3356228888

谢谢阅读

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值