#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 *);
};
*/
C++中的RTTI(runtime type information) 机制
最新推荐文章于 2022-03-31 11:43:32 发布