RTTI是运行阶段类型识别的简称。
可以让基类指针指向任何一个继承类的对象,但是如何知道指针指向的是哪种对象呢?
C++有3个支持RTTI的元素:
1)如果可能的话,dynamic_cast运算符将使用一个指向基类的指针来生成一个指向派生类的指针;否则,该运算符返回空指针。
2)typeid运算符返回一个指出对象类型的值。
3)type_info结构存储了有关特定类型的信息。
注意:只能将RTTI用于包含虚函数的类层次结构,原因在于只有对于这种类层次结构,才应该将派生对象的地址赋给基类指针。
1.dynamic_cast运算符
dynamic_cast不能回答“指针指向的是哪种对象”,但能够回答“是否可以安全将对象的地址赋给特定类型的指针”。
假设有下面层次结构:
struct Grand{
virtual void fun(){
cout << "Grand" << endl;
}
};
struct Superb :public Grand{
void fun(){
cout << "Superb" << endl;
}
};
struct Magnificent :public Superb{
void fun(){
cout << "Magnificent" << endl;
}
};
以及下面的指针:
Grand *pg = new Grand;
Grand *ps = new Superb;
Grand *pm = new Magnificent;
进行下面的类型转换:
Magnificent *p1 = (Magnificent*)pm; //安全:将Magnificent类型的指针指向Magnificent类型的对象
p1->fun(); //输出:Magnificent
Magnificent *p2 = (Magnificent*)pg; //不安全:基类地址赋给派生类指针
p2->fun(); //输出:Grand
Superb *p3 = (Magnificent*)pm; //安全:将派生类对象的地址赋给基类指针
p3->fun(); //输出:Magnificent
下面看用dynamic_cast进行转换:
Superb *p4 = dynamic_cast<Superb*>(pg); //不能安全的转换,返回空指针
cout << (p4 == NULL) << endl; //输出:1
所以可以这样使用:
Magnificent*p5;
if (p5 = dynamic_cast<Magnificent*>(ps))
p5->fun();
typeid运算符(和sizeof一样,是运算符,不是函数)能够确定两个对象是否为同种类型。可以接受两种参数:
1)类名
2)结果为对象的表达式
typeid返回一个对type_info对象的引用,其中type_info是在typeinfo头文件中定义的一个类,其重载了==和!=运算符。
typeid(Magnificent) == typeid(*pg);
注意:如果p是基类指针,并且指向一个派生类对象,并且基类中有虚函数,那么typeid(*p)返回p所指向的派生类类型,typeid(p)返回基类类型。如果基类没有虚函数,一样。
(但是经验证,好像typeid(p)返回的既不是基类类型,也不是派生类类型。)
#include <iostream>
using namespace std;
struct Grand{
virtual void fun(){
cout << "Grand" << endl;
}
};
struct Superb :public Grand{
void fun(){
cout << "Superb" << endl;
}
};
int main(){
Grand *ps = new Superb;
cout << (typeid(*ps) == typeid(Superb)) << endl; //输出1
cout << (typeid(ps) == typeid(Grand)) << endl; //输出0
cout << (typeid(ps) == typeid(Superb)) << endl; //输出0
return 0;
}
来看下面一个例子:
#include <iostream>
using namespace std;
class A{
public:
virtual void foo(){
cout << "A foo" << endl;
}
void pp(){
cout << "A pp" << endl;
}
};
class B :public A{
public:
void foo(){
cout << "B foo" << endl;
}
void pp(){
cout << "B pp" << endl;
}
void FunctionB(){
cout << "FunctionB" << endl;
}
};
int main(){
A a;
A* pa = &a;
B* pb = dynamic_cast<B*>(pa);
pb->FunctionB(); //输出:FunctionB
cout << ( pb == NULL) << endl; //输出1,说明不是安全类型转换
//pb->foo(); //不能运行
pb->pp(); //输出:B pp
return 0;
}
pb->FunctionB()和pb->pp()能够运行,是因为FunctionB和pp函数未使用任何成员数据,也不是虚函数,不需要this指针,也不需要动态绑定,可正常运行。
pb->foo不能运行,是因为调用了虚函数,编译器需要根据对象的虚函数指针查找虚函数表,但此时为空,为非法访问。
class B :public A{
public:
B(){ a = 0; }
void foo(){
cout << "B foo" << endl;
}
void pp(){
cout << "B pp" << endl;
}
void FunctionB(){
cout << a << ":FunctionB" << endl; //如果访问成员数据,就不能运行了
}
private:
int a;
};