C++学习笔记(二十七) typeinfo() 与 type_info类

1  用法  typeinfo(类名) typeinfo(对象)

2 要使用#include <typeinfo>

3 需要虚函数才可以使用RTTI ,才可以使用dymnaic_cast()<> 和 typeid()

4 typeinfo的几个接口 name() == != before()



#include <iostream>
#include <typeinfo> //使用typeinfo的头文件
using namespace std;

class A
{
public:
	virtual void f(){} //需要有虚函数 才可以用RTTi
};

class B: public A{};
class C:public A{};
class D:public A{};

int main()
{
	cout << typeid(A).name() <<endl; //1A
	cout << typeid(C).name() <<endl; //1C
	
	A *p1 = new A,*p2 = new B ,*p3 =new C,*p4 = new D,*p5 = new B ;
	//指针都是A*类型的 但还是可以识别出来 
	//typeid 返回type_info对象
	//  接口 name() 函数  返回类型名字 
	cout << typeid(*p1).name() <<endl; //1A (LINUX下) //class A(vs2010下)
	cout << typeid(*p2).name() <<endl; //1B //class B
	cout << typeid(*p3).name() <<endl;//1C //class C
	
	// == 比较类型是否相等 true 相等  false 不相等
	cout << (typeid(*p2) == typeid(*p5)) <<endl; 
	cout << (typeid(*p2) != typeid(*p5)) <<endl; 
	
	//LINUX GCC 下是这样的 before()  对象是参数的父类或者同类时 返回0   是参数的子类时返回1  
	//VS2010下实验的结果是 p1是p4父类时返回1 否则返回0
	cout << typeid(*p1).before(typeid(*p4)) <<endl;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值