typeid运算符

typeid( dataType ):基本类型:获取数据类型等,类类型 : 获取对象所属的类,所包含的成员,所存在的继承关系。
typeid( expression )

typeid 会把获取到的类型信息保存到一个 type_info 类型的对象里面,并返回该对象的常引用;当需要具体的类型信息时,可以通过成员函数来提取。

用法:
const typeinfo &var=typeid(datatype or expression )

cout<<var.name()<<var.raw_name()<<endl;

include <iostream.h>

include <typeinfo>

class Base{};
struct STU{};

void main(){
int temp=100;

const   type_info &tempinfo=typeid(temp);
cout<<tempinfo.raw_name()<<endl;

const type_info &tempunfo=typeid(22.5);
cout<<tempunfo.name()<<tempunfo.raw_name()<<endl;

class Base base;
const type_info &v1 = typeid(base); //获取一个对象的信息
cout<<v1.name()<<v1.raw_name()<<endl;

struct STU stu;

const type_info &v2 = typeid(stu);
cout<<v2.name()<<v2.raw_name()<<endl;

const type_info &v3 = typeid(char );

cout<<v3.name()<<v3.raw_name()<<endl;

const type_info &v4 = typeid(5.0/3);
cout<<v4.name()<<v4.raw_name()<<endl;
}

判断类型相等:
///typeid 会把获取到的类型信息保存到一个 type_info 类型的对象里面,并返回该对象的常引用;
//当需要具体的类型信息时,可以通过成员函数来提取。

include <iostream.h>

include <typeinfo>

class Base{};
struct STU{};

void main(){
char *str;
int a=2;
int b=10;
float f;
cout<<(typeid(a).name()==typeid(b).name())<<endl;
cout<<(typeid(int) == typeid(a))<<endl;
cout<<(typeid(int) == typeid(float))<<endl;
cout<<(typeid(int) == typeid(f))<<endl;

class Derive :public Base{};

class Base bs;
class Base *pbase;
class Derive de;
class Derive *pde;

cout<<(typeid(bs) == typeid(Base))<<endl;
cout<<(typeid(bs) == typeid(pbase))<<endl;
cout<<(typeid(bs) == typeid(de))<<endl;
cout<<(typeid(Base) == typeid(*pbase))<<endl;

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容