Usage of static_cast and dynamic_cast in C ++
Preface
There are many mandatory type conversion functions in the Framework layer source code of Android. People who are familiar with C code are generally used to the following forced conversion method:
double a = 89;int b = (int)a;
However, in C ++ code, it is not recommended to use the forced conversion style code such as C (type-id). We recommend that you use the standard type conversion character of C ++: static_cast and dynamic_cast.
Static_cast
The static_cast function prototype is as follows::
static_cast
(expression)
Description:
This operator converts expression to type-id.
The usage is as follows::
It is used to convert pointers or references between classes and subclasses in the class hierarchy. It is safe to transform upwards (to convert the pointer or reference of a subclass to the base class representation). To transform downward (to convert a base class pointer or reference to a subclass pointer or reference, because there is no dynamic type check, it is not safe. Used for conversion between basic data types. Converts a void pointer to a target pointer.
Example:
// 1. class conversion class Base {}; class Child: public Base {}; Child * a = new Child (); Base * B = static_cast
(A); // 2. Basic type conversion int I = 5; double r = static_cast (I); // 3. void * type conversion void * p = & I; int * s = static_cast (P );
Dynamic_cast
The function prototype of dynamic_cast is as follows::
dynamic_cast
(expression)
Description:
This operator converts expression to type-id objects. Type-id must be a class pointer, class reference, or void *. If type-id is a class pointer type, expression must also be a pointer, if type-id is a reference, expression must also be a reference.
Remarks:
I have not seen the use of dynamic_cast In the Android source code, so I will not give an example of the use of dynamic_cast here.