C++学习笔记(十七):RTTI

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

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

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

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

具体定义如下:

 1 class type_info{  
 2 public:   
 3     virtul ~type_info();   
 4     bool operator == (const type_info&rhs)const;   
 5     bool operator != (const type_info&rhs)const;   
 6     bool before(const type_info&rhs)const;   
 7     const char* name()const;   
 8 private:   
 9     type_info(const type_info& rhs);   
10     type_info& operator=(const type_info& rhs);  
11 }  

接口说明:

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

示例:

 1 #include <iostream>  
 2 #include <typeinfo>  
 3 using namespace std;  
 4   
 5 struct Base {};  
 6 struct Derived : Base {};  
 7 struct Poly_Base {virtual void Member(){}};  
 8 struct Poly_Derived: Poly_Base {};  
 9   
10 int main() {  
11   
12   int a;  
13   int * pa;  
14   cout << "int is: " << typeid(int).name() << endl;  
15   cout << "  a is: " << typeid(a).name() << endl;  
16   cout << " pa is: " << typeid(pa).name() << endl;  
17   cout << "*pa is: " << typeid(*pa).name() << endl << endl;  
18   
19   
20   Derived derived;  
21   Base* pbase = &derived;  
22   cout << "derived is: " << typeid(derived).name() << endl;  
23   cout << "*pbase is: " << typeid(*pbase).name() << endl;  
24   cout << "same type? ";  
25   cout << ( typeid(derived)==typeid(*pbase) ) << endl << endl;  
26   
27   
28   Poly_Derived polyderived;  
29   Poly_Base* ppolybase = &polyderived;  
30   cout << "polyderived is: " << typeid(polyderived).name() << endl;  
31   cout << "*ppolybase is: " << typeid(*ppolybase).name() << endl;  
32   cout << "same type? ";  
33   cout << ( typeid(polyderived)==typeid(*ppolybase) ) << endl << endl;  
34   return 0;  
35 }  
原文地址:https://www.cnblogs.com/hammerc/p/4033086.html