0
点赞
收藏
分享

微信扫一扫

C++:获取类型信息的typeid运算符

金刚豆 2022-04-05 阅读 63
c++

typeid 运算符用来获取一个类型的类型信息,他的操作对象可以是表达式,也可以是数据类型:

typeid( dataType )
typeid( expression )

typeid 会把获取到的类型信息保存到一个 type_info 类型的对象里面,并返回该对象的常量引用;可以通过成员函数name()来提取类型信息字符串,但C++没有规定name()返回的字符串格式,所以不同的编译器返回的格式是不一样的。

此外typeid还可以用于的判断。

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

class A{
};

int main()
{
	cout<<"the type of "<< 1 << " is:" << typeid(1).name() << endl;            //输出:the type of 1 is:i
	cout<<"the type of "<< "int" << " is:" << typeid(int).name() << endl;      //输出:the type of int is:i
	cout<<"the type of "<< 1.1 << " is:" << typeid(1.1).name() << endl;        //输出:the type of 1.1 is:d
	cout<<"the type of "<< "double" << " is:" << typeid(double).name() << endl;//输出:the type of double is:d

	A a;
	A *pa = &a;
	cout<<"the type of "<< "a" << " is:" << typeid(a).name() << endl;          //输出:the type of a is:1A
	cout<<"the type of "<< "A" << " is:" << typeid(A).name() << endl;          //输出:the type of A is:1A
	cout<<"the type of "<< "&a" << " is:" << typeid(&a).name() << endl;        //输出:the type of &a is:P1A
	cout<<"the type of "<< "pa" << " is:" << typeid(pa).name() << endl;        //输出:the type of pa is:P1A

    cout<<(typeid(A) == typeid(a))<<endl;    //输出:1
	cout<<(typeid(&a) == typeid(pa))<<endl;  //输出:1
	cout<<(typeid(A) == typeid(*pa))<<endl;  //输出:1
	cout<<(typeid(A) == typeid(pa))<<endl;   //输出:0
	return 0;
}
举报

相关推荐

C++ 运算符

c++赋值运算符

C++运算符重载

c++基础-运算符

C++(运算符重载)

【c++运算符重载】

C++ sizeof 运算符

0 条评论