Explicit type conversions in C + +

Source: Internet
Author: User

Type conversion Maybe everyone is not strange, int i; float J; j = (float) i; i = (int) J; Explicit conversions like this are very common, forcing type conversions may lose some of the data, so if you do not add (int) to do the cast, strict inspection of the compilation will be error, wide check the compilation will be reported warning. In the C language, pointers are 4-byte or 8-byte, so casts between pointers are like assignments between different integer types at the time of conversion, and the problem is that with the use of that pointer, you must ensure that the pointer does make such a cast. A common scenario is void* to different pointer types (such as memory allocations, parameter passing), char* and unsigned char* such conversions. There is also the time to read a file, directly map a structure to memory, write a file, a block of memory directly mapped to the structure. In C + +, however, there is a more appropriate and secure syntax specifically for displaying type conversions.

Mainly includes four kinds: static_cast, const_cast, reinterpret_cast, dynamic_cast. The four conversions are used in different ways, as described below:

  First, static_cast (static conversion)

Syntax: A = static_cast<typea> (B)

By converting B into the TypeA type, static_cast is the most commonly used conversion operator, which eliminates all the compiler warnings,static_cast that can be generated by generating type conversions, and is used for a well-defined transformation. Includes "security" transformations that the compiler allows us to do without coercion, and transformations that are less secure but clearly defined. The types of conversions included in static_cast include typical non-coercion type conversions, narrowing changes (loss of information), forced transformations using void*, implicit type transformations, and static positioning of class hierarchies (conversions between base classes and derived classes).

The description code is as follows:

1#include <iostream>2 using namespacestd;3 4 voidFuncint){}5 6 intMain () {7     inti =0x7fff;8     Longl;9     floatF;Ten     //Case 1, converting to wide data OneL =i; Af =i; -     //You can also use static_cast at this time -L = static_cast<Long>(i); thef = static_cast<float>(i); -      -cout <<"L ="<< L <<Endl; -cout <<"f ="<< F <<Endl; +      -     //Case 2, conversion to narrow data, possible loss of precision +i =l; Ai =F; atcout <<"i ="<< I <<Endl; -     //using static_cast At this point is similar to telling the compiler I know that this kind of thing happens, don't worry, also can eliminate the warning -i = static_cast<int>(l); -i = static_cast<int>(f); -     Charc = static_cast<Char>(i); -cout <<"C ="<< C <<Endl; in      -     //Case 3, casting the void* type to another type to     void* VP = &i; +     float* fp = (float*) VP;//This is a dangerous conversion -FP = static_cast<float*> (VP);//It's just as dangerous . the      *     //Case 4, implicit type conversion $     DoubleD =0.0;Panax Notoginseng     intx = D;//Automatic type conversion -x = static_cast<int> (d);//This statement is more pronounced theFunc (d);//Automatic type conversion +Func (static_cast<int> (d));//This statement is more pronounced A}

The more important application is the conversion between the base class and the derived class

Class base{};   Class Derv:public base{};   Derv DD;   Base BB = static_cast (dd);//conversions between types that have an inheritance relationship   
Base *PB = new Base; Derv *PD = static_cast (PB);//base class to inherit class derv* pd1 = new Derv; base* PB1 = static_cast (PD1);//Inherit class pointer to parent class pointer

Second, const_cast (constant conversion )
Syntax: A = const_cast<typea> (B)
This operator can be used to remove a const or volatile property of an object. TypeA must be a pointer or reference.
1#include <iostream>2 using namespacestd;3 intMain () {4     Const inti =0;5     int* J = (int*) &i;//Deprecated Methods6j = const_cast<int*> (&i);7cout << *j <<Endl;8*j =Ten;9cout << *j <<" "<< I <<Endl;Ten}


  Third, reinterpret_cast (re-interpretation conversion)

Syntax: A = reinterpret_cast<typea> (B)

This is the most unsafe conversion, the most likely problem, reinterpret_cast the object as a pattern, as if it is a completely different type of object, this is a low-level bit operation, modified the operand type, but only re-interpretation of the object's bit model and not binary conversion, Before using reinterpret_cast to do anything, you actually always need it back to the original type.

Syntactically, this operator is used only for pointer-type conversions (The return value is a pointer). It is used to convert one type pointer to another type pointer, which simply re-interprets the pointer's type at compile time.

This operator basically does not consider whether the conversion type is related.

The nature of the reinterpret_cast (http://blog.csdn.net/coding_hello/archive/2008/03/24/2211466.aspx) is a good explanation for the experiment reinterpret_ Cast does not make binary conversion features. I like to understand this operator from the C language point of view, just like the pointer cast in C, it just assigns the address to the new pointer, and the other does not change, only when the new pointer is used, to make a different interpretation. Look at the following example:

1#include <iostream>2 using namespacestd;3 Const intSZ = -;4 5 structX {6     intA[sz];7 };8 9 voidPrint (x*x) {Ten      for(inti =0; I < sz; i++) Onecout << X->a[i] <<' '; Acout << Endl <<"-------------------------"<<Endl; - } -  the intMain () { - x x; -Print (&x);//output a struct body array that has not been initialized -     int* XP = reinterpret_cast<int*> (&AMP;X);//re-interpret the conversion, get the address of X and convert it to an integer pointer +      for(int* i = XP; I < XP + sz; i++)//The pointer is then used to iterate through the array, placing each integer element at 0 -*i =0; +Print (reinterpret_cast<x*>(XP)); APrint (&x); at}

The idea of reinterpret_cast is that when it is necessary to use it, something has been converted into a different type so that it cannot be used for the original purpose of the type, unless it is converted back again. Here the print call transfers back to x*. XP is only used as a int*, which is a re-interpretation of the original X. Using Renterpret_cast is often not a sensible approach, but it is useful when needed.

Reinterpret_cast Common scenarios include the following:

1) Normal pointer conversion, t*->u*->t*, to ensure that the t* after some column conversion value is unchanged

For example, the different types of pointers exist in a container, vectors can be stored int*,char*,string* and other pointers, as long as there are other ways to determine the original type of a void* is t*, the standard guarantee reinterpret_cast (V[i]) can get the original value.

2) Do your own memory allocator, you can convert T * to u*, this time you may want to pay attention to the problem of the byte.


  Iv. dynamic_cast (Dynamic conversion)

Grammar:a=dynamic_cast<typea> (B)

The operator converts B to an object of type TypeA. TypeA must be a pointer to a class, a reference to a class, or void *;

The dynamic_cast conversion is performed at run time, and one of its benefits is that it will run as a type check, and if the object's type is not the desired type, it will return NULL when the pointer is converted and throw a Std::bad_cast exception when referencing the conversion.

Dynamic_cast generally only type conversions between pointers to inheriting class objects or between references. If there is no inheritance relationship, the converted class has a pointer to the virtual function object to convert.

1    structA {2     Virtual voidf () {}3   };4   structD | PublicA {};5   structC {};6  7   voidf () {8 A;9 b b;Ten   OneA * ap = &b; Ab* B1 = dynamic_cast (&a);//NULL, because ' a ' is not a ' B ' -b* b2 = dynamic_cast (AP);//' B ' -c* C = dynamic_cast (AP);//NULL. the   -a& ar = dynamic_cast (*AP);//Ok. -b& br = dynamic_cast (*AP);//Ok. -c& cr = dynamic_cast (*AP);//Std::bad_cast +}

Explicit type conversions in C + +

Related Article

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.