Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

The C++ standard library

The C++ standard library

In C++, is part of the standard library; it provides Run-Time Type Identification (RTTI) functionality. RTTI allows a program to determine the type of an object at runtime. This is achieved by using the typeid operator and the type_info class.

type_info class is an abstract base class that provides an interface for type information. Each type has an associated type_info object, which can be accessed through the typeid operator.

Syntax

Related main syntax:

Type information class type_info

typeinfo header provides runtime support for type information. It mainly contains two core components:std::type_info class and typeid new operator.typeinfo allow a program to obtain an object's type information at runtime, which is very useful in polymorphic and type-safe code. Below is a detailed introduction to typeinfo :

std::type_info class

std::type_info The class is typeinfo the core class of the header, used to describe a type. It provides several member functions for querying type information. Common member functions are as follows:

typeid operator

typeid operator is used to obtain type information at runtime.typeid can act on an object (a pointer or reference with polymorphic behavior) or a type (without instantiating an object).

Example

Below is an example using A simple example of :

Example

#include

#include

class

Base

{

public

:

   

virtual

void

show

(

)

{

std

::

cout

<<

"Base show"

<<

std

::

endl

;

}

}

;

class

Derived

:

public

Base

{

public

:

   

void

show

(

)

override

{

std

::

cout

<<

"Derived show"

<<

std

::

endl

;

}

}

;

int

main

(

)

{

    Base

basePtr

=

new

Derived

(

)

;

    Base

basePtr2

=

new

Base

(

)

;

    std

::

cout

<<

"Type of basePtr: "

<<

typeid

(

basePtr

)

.

name

(

)

<<

std

::

endl

;

    std

::

cout

<<

"Type of basePtr2: "

<<

typeid

(

basePtr2

)

.

name

(

)

<<

std

::

endl

;

   

if

(

typeid

(

basePtr

)

==

typeid

(

Derived

)

)

{

        std

::

cout

<<

"basePtr is of type Derived"

<<

std

::

endl

;

   

}

else

{

        std

::

cout

<<

"basePtr is not of type Derived"

<<

std

::

endl

;

   

}

   

delete

basePtr

;

   

delete

basePtr2

;

   

return

0

;

}

Output result:



Type of basePtr: 9Derived  // 注意:typeid的name()返回的类型名称可能因编译器而异

Type of basePtr2: 8Base     // 同上

basePtr is of type Derived

Notes

provides a method to identify object types at runtime, which is very useful for implementing polymorphism and type safety. However, developers should use RTTI with caution to avoid unnecessary performance overhead and potential type errors.