C + + coercion type conversion

Source: Internet
Author: User

C-style forced type conversion (type cast) is simple, no matter what type of conversion is:

Type B = (type) a

C + + Style type conversion provides 4 types of conversion operators to handle applications in different situations.

  const_cast, the literal understanding is to go to the const attribute.

  static_cast, the name is understood to be a static type conversion. such as int converted to char. (Basic type conversion)

  dynamic_cast, the name is understood to be a dynamic type conversion. such as a polymorphic type conversion between a subclass and a parent class.

  reinterpret_cast, only the type is re-interpreted, but there is no binary conversion. (pointer type conversion)



Removes the const or volatile property of a type. 

 struct  SA {  int  i;  };   const  SA RA;  // // Modify const type directly, compile error  &rb = const_cast<sa&>   ten;


Similar to C-style casts. Unconditional conversion, static type conversion. For:

1. conversion between a base class and a subclass where a child class pointer is safe to convert to a parent pointer, but it is unsafe for a parent pointer to be converted to a child class pointer. (Dynamic type conversion between base class and subclass recommended with dynamic_cast)

2. Basic data type conversions. enum, struct, int, char, float, and so on. Static_cast cannot perform conversions between unrelated types (such as non-base classes and subclasses).

3. Convert the null pointer to a null pointer of the target type.

4. convert any type of expression to void type.

5. static_cast cannot remove the const, Volitale attribute of the type (with Const_cast).

int 6 ; double d = static_cast<double//  Basic type conversion int *pn = &N;  double *d = static_cast<double// unrelated type pointer conversion, compile error (required with reinterpret_cast, Of course the result is wrong after conversion)void *p = static_cast<void// any type converted to void type


Conditional conversions, dynamic type conversions, run-time type security checks (conversion failure returns NULL):

1. Secure the conversion between the base class and the subclass.

2. You must have a virtual function .

3. Cross-conversion between different subclasses of the same base class. But the result is null.


   classBaseClass { Public:intM_inum; Virtual voidfoo () {}; The  // base class must have a virtual function. Maintain polymorphic properties to use dynamic_cast }; classDerivedClass: PublicBaseClass { Public:Char*m_szname[ -]; voidBar () {};  }; BaseClass* PB =NewDerivedClass (); DerivedClass*PD1 =Static_cast<derivedclass *> (pb);  // Subclass-Parent class, static type conversion, correct but not recommended DerivedClass*PD2 =Dynamic_cast<derivedclass *> (pb);  // Subclass, parent class, dynamic type conversion, correct BaseClass* PB2 =NewBaseClass (); DerivedClass*pd21 = Static_cast<derivedclass *>(PB2);  // Parent class--subclass, static type conversion, Danger! Access Subclass M_szname member  out of boundsDerivedClass*pd22 = Dynamic_cast<derivedclass *>(PB2); //Parent class, subclass, dynamic type conversion, secure. The result is null



The reinterpret_cast operator replaces the use of most other C-style type conversions. reinterpret_cast Converts a pointer to another pointer type, converts a number to a pointer, or converts a pointer to a number . As with the C-style type conversion, when using the reinterpret_cast operator, the user should know what to do with themselves. Sometimes, only C-style type conversions work, but this is not to say that reinterpret_cast should never be used. The following example shows a simple memory-allocation program that returns a 100-character buffer with a void pointer. The Main () function assigns the returned result to a character-type pointer. The translation rules for C + + are not the same as C. In C + + conversion rules, you cannot implicitly convert void* to char*, so you need to type-convert. The following uses a type conversion of reinterpret_cast instead of C language style

#include <iostream>#include<cstring>//Create a buffer.// void*Getmem () {Static Charbuf[ -];returnbuf;}intMain () {Char* CP = reinterpret_cast<Char*>(Getmem ()); strcpy (CP,"Hello, Woody."); Std::cout<<CP;return 0; }

  reinterpret_cast only re-interprets the type, but does not perform a binary conversion:

1. The type of conversion must be a pointer, reference, arithmetic type, function pointer, or member pointer.

2. Convert at the bit level. It can convert a pointer to an integer, or an integer to a pointer (a pointer is converted to an integer, the integer is converted to the original type of pointer, and the original pointer value can be obtained). However, you cannot convert an instance that is not 32bit to a pointer.

3. The most common use is to convert between function pointer types.

4. Portability is difficult to ensure.

   intDoSomething () {return 0;}; typedefvoid(*funcptr)             (); //Funcptr is a pointer to a function that has no arguments and a return value of type voidfuncptr funcptrarray[Ten]; //an array of 10 funcptrs pointers Let's assume you want (for some inexplicable reason) to put a pointer to the following function into the Funcptrarray array:funcptrarray[0] = &dosomething; //Compile Error! Type mismatch, reinterpret_cast can let the compiler look at them your way: Funcptrarrayfuncptrarray[0] = reinterpret_cast<funcptr> (&dosomething); //convert between different function pointer types
the operator uses more. The operator modifies the operand type, but simply re-interprets the given object's bit model without binary conversion.
int New int  ; double *d=reinterpret_cast<double*> (n);
after the calculation, D contains useless values. This is because reinterpret_cast only replicates n bits to D and does not perform the necessary analysis. Therefore, it is prudent to use reinterpret_cast.reinterpret_cast is meant to map to a completely different type of meaning, and this keyword is used when we need to map the type back to the original type. The type we map to is just for the sake of the trick and other purposes, which is the most dangerous of all mappings. (This is the exact words in C + + programming idea)static_cast and reinterpret_cast differ mainly in multiple inheritance, such as
class A {    public:    intclass  B     {  public:     int.class public public B {};
so for the following code:
C c;printf ("%p,%p,%p", &c, reinterpret_cast<b*> (&c), static_cast <B*> (&c));
The first two output values are the same, and the last one offsets 4 bytes on the original basis, because Static_cast calculates the offset of the parent-child class pointer conversion and converts it to the correct address (C has m_a,m_b in it, translates to b* pointer and points to m_b). But Reinterpret_cast does not do this layer of conversion. Therefore, you need to be cautious about using reinterpret_cast.

Go to the const attribute with const_cast.

Basic type conversion with static_cast.

A type conversion between polymorphic classes is used with Daynamic_cast.

Different types of pointer-type conversions with Reinterpreter_cast.

C + + coercion type conversion

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.