编程语言
首页 > 编程语言> > C++ Runtime Type Identification(RTTI)

C++ Runtime Type Identification(RTTI)

作者:互联网

What is RTTI for?

The intent of RTTI is to provide a standard way for a program to determine the type of object during runtime.

How Does RTTI Work?

Caution

RTTI works only for classes that have virtual functions.

class Grand{has virtual methods};
class Superb: public Grand{...};
class Magnificent : public Superb{...};

Grand* pg = new Grand;
Superb * pm = dynamic_cast<Superb *>(pg); 
// This code asks whether the pointer pg can be type cast safely to the type Superb*. If it can, the operator renturns the address of the object. Otherwise it returns 0, the null pointer. 


You can invoke the Say() function safely:

if(ps = dynamic_cast<Superb *>(pg))
    ps->Say();

The typeid operator and type_info Class

The typeid operator returns a reference to a type_info object, where type_info is a class defined in the typeinfo header file (formerly typeinfo.h). The type_info class overloads the == and != operators so that you can use these operators to compare types.
For example, the following expression evalluates to the bool value true if
pg points to a magnificent object and to false otherwise:

typeid(Magnificent) == typeid(*pg);
// if pg happens to be a null pointer, the program throws a bad_typeid exception.

cout<< typeid(*pg).name() <<"\n";

标签:typeid,RTTI,pointer,Identification,pg,type,operator,Runtime,Type
来源: https://blog.csdn.net/lilele12211104/article/details/111239599