C++ typeinfo用法总结

目录

一.name操作

二.!=和==操作

三.总结说明


一.name操作

1.语法:

typeid(data).name();

填入参数,参数可以是数据类型也可以是数据,该函数以C风格的字符串指针形式返回该数据的类型名。

2.示例:

C++代码:

#include<iostream>
#include<vector>
#include<list>
#include<string>
#include<map>
#include<typeinfo>
using namespace std;

class example
{
private:
	string name;
};

int main()
{
	int a;
	int* ptr;
	vector<string> vec;
	list<int> lis;
	string str;
	map<string, int> m1;
	example e1;

	//typeid(data).name();

	cout << "int is:" << typeid(int).name() << endl;
	cout << "-------------------" << endl;
	cout << "a is:" << typeid(a).name() << endl;
	cout << "-------------------" << endl;
	cout << "ptr is:" << typeid(ptr).name() << endl;
	cout << "-------------------" << endl;
	cout << "vec is:" << typeid(vec).name() << endl;
	cout << "-------------------" << endl;
	cout << "lis is:" << typeid(lis).name() << endl;
	cout << "-------------------" << endl;
	cout << "str is:" << typeid(str).name() << endl;
	cout << "-------------------" << endl;
	cout << "m1 is:" << typeid(m1).name() << endl;
	cout << "-------------------" << endl;
	cout << "e1 is:" << typeid(e1).name() << endl;
	cout << "-------------------" << endl;

	system("pause");
	return 0;
}

程序运行结果:

二.!=和==操作

1.语法:

typeid(data1) == typeid(data2);
typeid(data3) != typeid(data4);

判断两个数据是否相同,参数可以是数据类型也可以是数据

2.示例:

C++代码:

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

class base
{
};

class derive :public base
{
};

int main()
{
	base b1;
	derive d1;
	if (typeid(b1) == typeid(base))
	{
		cout << "b1 is a base" << endl;
	}
	
	if (typeid(d1) != typeid(base))
	{
		cout << "d1 is not a base" << endl;
	}

	if (typeid(d1) == typeid(derive))
	{
		cout << "d1 is a derive" << endl;
	}

	string name;
	if (typeid(name) == typeid(string))
	{
		cout << "name is a string" << endl;
	}


	system("pause");
	return 0;
}

程序运行结果:

三.总结说明

1.和sizeof这类的操作符一样,typeid是C++的关键字之一。
2.typeid操作符的返回结果是名为type_info的标准库类型的对象的引用(在头文件typeinfo中定义)

3.typeid(*this) -- 返回一个type_info对象,关联至this指针所指对象
4.C++并没有规定typeid实现标准,各个编译器可能会不一样。
5.编译器会为每一种typeid操作的类型生成一份保存在数据段的type_info数据。
6.每种类型的type_info数据长度依赖于类型名称,至少9个字节。

7.typeid运算符会返回一个type_info对象,其中储存着与类型相关的种种信息。

 参考文章:(56条消息) C++中的typeInfo用法总结_非晚非晚的博客-CSDN博客_typeinfo
 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值