这个知识点被遗漏了,可以结合之前的这篇文章看类型转换这个知识点。

RTTI(Run-Time Type Information,运行时类型信息)即程序能够使用基类的指针或引用来检查这些指针或引用所指的对象的实际派生类型。

C++中有两个操作符提供RTTI
typeid:返回指针或引用所指对象的实际类型。
dynamic_cast:将基类类型的指针或引用安全地转换为派生类型的指针和引用。(点击这里查看

typeid
头文件:# include<typeinfo>
语法--两种形式:typeid (type) 、typeid (expression)即任意表达式或类型名。
常见的用途:比较两个表达式的类型,或者将表达式的类型与特定类型相比较。
typeid返回类型:const type_info&;

具体定义如下:

 class type_info{
public:
virtul ~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()const;
private:
type_info(const type_info& rhs);
type_info& operator=(const type_info& rhs);
}

接口说明:

operator ==和operator!=:比较操作符,返回两个类型是否为(或不为)同一类型(注:基类和派生类不为同一类型!)。
before:若在类型排序中,该类型先于rhs的类型则返回true。
name:返回类型对应的名字(具体所用的值,依赖于具体编译器)(以\0结束的字符串)。
注意:type_info类的默认构造函数和复制构造函数以及赋值操作符都定义为private,故不能定义或复制type_info类型的对象。程序中创建type_info对象的唯一方法是使用typeid操作符。

示例:

 #include <iostream>
#include <typeinfo>
using namespace std; struct Base {};
struct Derived : Base {};
struct Poly_Base {virtual void Member(){}};
struct Poly_Derived: Poly_Base {}; int main() { int a;
int * pa;
cout << "int is: " << typeid(int).name() << endl;
cout << " a is: " << typeid(a).name() << endl;
cout << " pa is: " << typeid(pa).name() << endl;
cout << "*pa is: " << typeid(*pa).name() << endl << endl; Derived derived;
Base* pbase = &derived;
cout << "derived is: " << typeid(derived).name() << endl;
cout << "*pbase is: " << typeid(*pbase).name() << endl;
cout << "same type? ";
cout << ( typeid(derived)==typeid(*pbase) ) << endl << endl; Poly_Derived polyderived;
Poly_Base* ppolybase = &polyderived;
cout << "polyderived is: " << typeid(polyderived).name() << endl;
cout << "*ppolybase is: " << typeid(*ppolybase).name() << endl;
cout << "same type? ";
cout << ( typeid(polyderived)==typeid(*ppolybase) ) << endl << endl;
return ;
}
04-24 15:34
查看更多