RTTI

一. 对于存在父子关系的类,当父亲指针指向孩子对象时,有时候需要确定具体指向那个孩子,那么可以用typeid函数确定,但是只能用于存在虚函数的继承层次里,例如:

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

class one
{
	class nested{};
	nested* n;
public:
	one()
	{
		n = new nested();
	}
	~one()
	{
		delete n;
	}
	nested* N()
	{
		return n;
	}
};

int main()
{
	one o;
	cout << typeid(*o.N()).name() << endl;

	system("pause");
	return 0;
}

二. 通过RTTI可以确定指针类型,例如:

#include <iostream>
using namespace std;

class d1
{
public:
	virtual void foo(){}
};

class d2
{
public:
	virtual void bar(){}
};

class mi : public d1, public d2{};

class mi2 : public mi{};

int main()
{
	d2* D2 = new mi2;

	bool b1 = (typeid(D2) == typeid(mi2*));
	bool b2 = (typeid(D2) == typeid(d2*));

	cout << "b1=" << b1 << endl;
	cout << "b2=" << b2 << endl;


	system("pause");
	return 0;
}

结果:

b1=0
b2=1


三. 运行时类型识别对于void*不起作用,例如:


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

class strimpy
{
public:
	virtual void happy(){}
	virtual void joy(){}
};

int main()
{
	void* v = new strimpy;
	strimpy* s = dynamic_cast<strimpy*>(v); //error C2681: 'void *' : invalid expression type for dynamic_cast
	cout << typeid(*v).name() << endl; //error C2100: illegal indirection

	system("pause");
	return 0;
}

四. 用模板来使用RTTI

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

template<int id>
class announce
{
public:
	announce()
	{
		cout << typeid(*this).name() << " constructor" << endl;
	}
	~announce()
	{
		cout << typeid(*this).name() << " destructor" << endl;
	}
};

class x : public announce<0>
{
	announce<1> m1;
	announce<2> m2;
public:
	x()
	{
		cout << "x::x()" << endl;
	}
	~x()
	{
		cout << "x::~x()" << endl;
	}
};

int main()
{
	x X;

	system("pause");
	return 0;
}

结果:

class announce<0> constructor
class announce<1> constructor
class announce<2> constructor
x::x()


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值