Four explicit data-type conversion functions in C + +

Source: Internet
Author: User

1 reinterpret_cast (conversion is implemented during compilation)

The Reinterpret_cast type conversion function converts a pointer of one type into a pointer to another type. This conversion is not used to modify the format in which the value data of a pointer variable is stored (without changing the value of the pointer variable) and can be done simply by interpreting the type of the pointer during compilation.

Reinterpret_cast can convert a pointer value to an integer number. However, it cannot be used for conversions that are not pointer types, otherwise they will not be compiled.

When to use reinterpret_cast for data type conversions:

(1) Converts the base type pointer to a pointer of another type.

For example:

Conversion of the base type pointer

double d = 9.3;
double *pd = &d;
int *pi = reinterpret_cast<int *>(pd);//相当于隐式转换int * pi = (int *)pd;

(2) Converts a pointer to a class to a pointer to another class.

Conversion of class pointer type:

class A{};
class B{};
A* pa = new A;
B* = reinterpret_ cast<B*>pa;

(3) Non-pointer type cannot be converted

For example:

converting an int type to a float type cannot be converted to a successful

int i = 8;

Double dl = reinterpret_cast<double> (i);

(4) cannot convert a const pointer to a pointer of type void*

Const int* PCI = 0;

void *PV = reinterpret_cast<void*> (PCI);

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.