This knowledge point has been omitted and can be combined with the previous article to see the type conversion of this knowledge point.
RTTI (run-time type information, run-time types information) is the ability for a program to use pointers or references to the base class to examine the actual derived types of the objects referred to by those pointers or references.
There are two operators in C + + that provide Rtti
typeID: Returns the actual type of the object that the pointer or reference refers to.
dynamic_cast: A pointer or reference to a base class type is safely converted to a pointer and reference of a derived type. (Click here to view)
typeID
Header file: # include<typeinfo>
Syntax-Two forms: typeID (Type), typeid (expression), either an arbitrary expression or a type name.
Common uses: To compare the types of two expressions, or to compare the type of an expression to a particular type.
typeID return type: const type_info&;
It is defined as follows:
1 classtype_info{2 Public: 3Virtul ~Type_info (); 4 BOOL operator== (ConstTYPE_INFO&RHS)Const; 5 BOOL operator!= (ConstTYPE_INFO&RHS)Const; 6 BOOLBefore (ConstTYPE_INFO&RHS)Const; 7 Const Char* Name ()Const; 8 Private: 9Type_info (Consttype_info&RHS); Tentype_info&operator=(Consttype_info&RHS); One}
Interface Description:
operator = = and operator! =: comparison operator, returns whether two types are (or are not) the same type (note: base class and derived class are not of the same type!) )。
Before: Returns True if the type precedes the RHS type in the type sort.
Name: Returns the names of the types (the specific values used, depending on the specific compiler) (the string ending with a.
Note: The default constructor and copy constructor of the Type_info class and the assignment operator are defined as private, so objects of type type_info cannot be defined or copied. The only way to create a Type_info object in a program is to use the typeid operator.
Example:
1#include <iostream>2#include <typeinfo>3 using namespacestd; 4 5 structBase {}; 6 structDerived:base {}; 7 structPoly_base {Virtual voidMember () {}}; 8 structPoly_derived:poly_base {}; 9 Ten intMain () { One A intA; - int*PA; -cout <<"int is:"<< typeID (int). Name () <<Endl; thecout <<"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; Acout <<"Derived is:"<< typeid (derived). Name () <<Endl; atcout <<"*pbase is:"<< typeid (*pbase). Name () <<Endl; -cout <<"same type?"; -cout << (typeID (derived) ==typeid (*pbase)) << Endl <<Endl; - - - poly_derived polyderived; inpoly_base* ppolybase = &polyderived; -cout <<"polyderived is:"<< typeid (polyderived). Name () <<Endl; tocout <<"*ppolybase is:"<< typeid (*ppolybase). Name () <<Endl; +cout <<"same type?"; -cout << (typeID (polyderived) ==typeid (*ppolybase)) << Endl <<Endl; the return 0; *}
C + + Learning Note (17): RTTI