C++中的RTTI(runtime type information) 机制

#include <iostream>
#include <typeinfo>


using namespace std;

class Shape {
public:
	virtual void Print()=0;
};


class Circle:public Shape {
public:
	virtual void Print() override {
		cout << "this is a Circle" << endl;
	}
};


class Square:public Shape {
public:
	virtual void Print() override {
		cout << "this is a Square" << endl;
	}
};


int main() {
	Shape *s[2];
	s[0] = new Circle;
	s[1] = new Square;
	for(int i=0;i<2; i++) {
		//1.运行时转型,必须含有虚函数virtual,安全向下转型
		//RTTI(runtime type information)
		if(dynamic_cast<Circle*>(s[i])) {
			cout << "hello Circle" << endl;
			s[i]->Print();
		}
		if(dynamic_cast<Square*>(s[i])) {
			cout << "hello Square" << endl;
			s[i]->Print();
		}
	}
	cout << typeid(*s[0]).name() << endl; //typeid是运行时期的事情,也就是动态类型
	cout << typeid(Circle).name() << endl;
	if(typeid(Circle).name() == typeid(*s[0]).name()) {
		cout << "p is point to a Circle object" << endl;
		((Circle*)s[0])->Print();
	}
	
	//type_info ti = typeid(Circle);  //private
	return 0;
}


/*
class type_info
{
public:
    virtual ~type_info();
    bool operator==(const type_info& _Rhs) const; // 用于比较两个对象的类型是否相等
    bool operator!=(const type_info& _Rhs) const; // 用于比较两个对象的类型是否不相等
    bool before(const type_info& _Rhs) const;

    // 返回对象的类型名字,这个函数用的很多
    const char* name(__type_info_node* __ptype_info_node = &__type_info_root_node) const;
    const char* raw_name() const;
private:
    void *_M_data;
    char _M_d_name[1];
    type_info(const type_info& _Rhs);
    type_info& operator=(const type_info& _Rhs);
    static const char * _Name_base(const type_info *,__type_info_node* __ptype_info_node);
    static void _Type_info_dtor(type_info *);
};

*/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值