Usage of static_cast and dynamic_cast in C ++

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.