/*对于RTTI(运行阶段类型识别)主要包含dynamic_cast,typeid,type_info*/
1.dynamic_cast
对于指针转换,从派生类转换成基类指针将会返回对象地址,如果转换错误将会返回NULL
对于引用转换,转换错误将会引发bad_cast异常,在头文件<typeinfo>
2.typeid
typeid()返回一个type_info对象引用
3.type_info
获取类信息,可以利用name()方法来获取类名(并非一定),也可以进行比较
//rtti.h
#ifndef _RTTI_H_
#define _RTTI_H_
#include<iostream>
#include<string>
/*对于RTTI(运行阶段类型识别)主要包含dynamic_cast,typeid,type_info*/
using namespace std;
class A
{
private:
int a1;
double a2;
public:
A(const int &t1, const double &t2) :a1(t1), a2(t2){}
virtual ~A(){}
virtual void show()const{ cout << "class A: a1=" << a1 << ",a2=" << a2 << endl; }
virtual void set(const int &t1, const double &t2){ a1 = t1; a2 = t2; }
};
class B :public A
{
private:
string b;
public:
B(const int &t1, const double &t2, const string &str) :A(t1, t2), b(str){}
virtual ~B(){}
virtual void show()const{ cout << "class B: b=" << b << endl; }
virtual void set(const string &str){ b = str; }
};
class C :public B
{
private:
char ch;
public:
C(const int &t1, const double &t2, const string &str, const char &c) :B(t1, t2, str), ch(c){}
~C(){}
void show()const{ cout << "class C: ch=" << ch<< endl; }
virtual void set(const char &c){ ch = c; }
};
#endif //_RTTI_H_
//main.cpp
//#include<iostream>
#include<cstdlib>
#include<ctime>
#include"windows.h"
#include"rtti.h"
#include<typeinfo>
const int TEST = 6;
using namespace std;
A* select();
int main()
{
srand(time(0));
B *bpt;
A *apt;
for (int i = 0; i < TEST; i++)
{
apt = select();
cout << "Now, I'm a " << typeid(*apt).name() << " class\n";
//typeid(*apt)返回一个type_info对象引用
if (bpt = dynamic_cast<B *>(apt))
/*派生类可以向基类转换并返回地址,转换失败返回NULL(对于指针)
对于引用将不会返回NULL,将会返回bad_cast异常(在typeinfo头文件声明)*/
bpt->show();
if (typeid(*apt) == typeid(C))
cout << "It really a C class\n";
cout << "***********Test Over************\n";
}
system("pause");
return 0;
}
A* select()
{
A *temp;
switch (rand() % 3)
{
case 0:temp = new A(rand() % 50, double(rand() % 20));
break;
case 1:temp = new B(rand() % 50, double(rand() % 20),"I'm B class");
break;
case 2:temp = new C(rand() % 50, double(rand() % 20), "I'm B class", 'C');
break;
default:temp = nullptr;
}
return temp;
}
程序运行结果如下: