The new C + + type conversion is known

Source: Internet
Author: User
Tags volatile

C Language Type Conversion

The type conversion method used in C language is generally cast with coercion type, syntax: (type specifier) (expression), for example: (float) A converts a to a real type, (int) (X+Y) Converts the result of x+y to an integral type.
The type conversion form of C, when assigned, can make people feel less sophisticated and less restrictive because, regardless of the value of an expression, the system automatically converts it to the type of the left variable of the assignment operator.

C + + type conversions

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.
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.

Const_cast:

The operator is used to modify the const or volatile properties of a type. In addition to const or volatile adornments, the type_id and expression types are the same.

#include <stdio.h>using namespacestd;structdata{intvalue;};intMainintARGC, _tchar*argv[]) {    ConstData data1 = {Ten}; //Data1.value =;//error C3892: "Data1": Cannot assign a value to a constantData &data2 = Const_cast<data &>(DATA1); Data2.value= -; printf ("Data1.value =%d Data2.value =%d\n", Data1.value,data2.value); Const intA =Ten; int*b = const_cast<int*> (&a); *b = -; printf ("A =%d b = = &a is%d\n", B = &a); System ("Pause"); return 0;}

dynamic_cast
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;virtualvoid foo () {};//The base class must have a virtual function. Maintain multiple features to use dynamic_cast};classDerivedClass: PublicBaseClass { Public:Char*m_szname[ -];voidBar () {};}; BaseClass* PB =Newderivedclass ();D Erivedclass*PD1 = Static_cast<derivedclass *> (pb);//Subclass--Parent class, static type conversion, correct but not recommendedDerivedClass *pd2 = Dynamic_cast<derivedclass *> (pb);//Subclass--Parent class, dynamic type conversion, correctBaseClass* PB2 =NewBaseClass ();D Erivedclass*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 

Static_cast:

① is used for the conversion of pointers or references between base classes (parent classes) and derived classes (subclasses) in a class hierarchy.
It is safe to make an upstream conversion (to convert a pointer or reference from a derived class to a base class representation).
When you make a downstream conversion (a base class pointer or reference is converted to a derived class representation), it is unsafe because there is no dynamic type checking.
② is used for conversions between basic data types, such as converting int to char, and converting int to enum. The security of this conversion is also to be ensured by the developer.
③ converts a null pointer to a null pointer of the target type. (int* to long* error C2440: "static_cast": Cannot convert from "int *" to "long *")
④ converts any type of expression to a void type.

Reinterpret_cast:

reinterpret_cast<type-id> (expression)
Type-id must be a pointer, reference, arithmetic type, function pointer, or member pointer. It can convert a pointer to an integer, or it can convert 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).

The primary is to re-force the value of the original address to the new type.

Comparison of type conversions between Reinterpret_cast and static_cast:

#include <stdio.h>using namespacestd;classa{ Public:    intm_a;};classb{ Public:    intM_b;};classC: PublicA Publicb{};intMainintARGC, _tchar*argv[]) {C* C =NewC (); C->m_a =1; C->m_b =2; A* A1 = Static_cast<a*>(c); A* A2 = reinterpret_cast<a*>(c); B* B1 = static_cast<b*>(c); B* B2 = reinterpret_cast<b*>(c); printf ("c =%p,a1 =%P,B1 =%p\n", C,A1,B1); printf ("c =%p,a2 =%P,B2 =%p\n", C,A2,B2); printf ("a1.m_a =%d, B1.m_b =%d\n",a1->m_a,b1->m_b); printf ("a2.m_a =%d, B2.m_b =%d\n",a2->m_a,b2->m_b); System ("Pause"); return 0;}

Operation Result:

00392950 00392950 00392954  0039295000392950,b2 = 00392950121  b2.m_b = 1

From the running results can be clearly seen, the use of reinterpret_cast for casting B2 is directly from the address of C, the C is converted to B2, and when using Static_cast, B1 is carried out a sizeof (a) an offset displacement, That is, in the case of multiple inheritance, it is safe to use static_cast to convert the object pointer of a subclass into a pointer to a base class object. The purpose of reinterpret_cast is to redefine the type unless you explicitly want to point to the piece of memory that you want to define to the target you want to convert, otherwise use caution.

One use example of reinterpret_cast:

#include <stdio.h>using namespaceStd;typedefvoid(*funcptr) (); typedefint(*FuncPtr2) ();voidfun1 () {}intfun2 () {return Ten;}intMainintARGC, _tchar*argv[]) {funcptr fun[Ten]; fun[0] = &fun1; //fun[1] = &fun2;//error C2440: "=": Cannot convert from "int (__cdecl *) (void)" to "Funcptr"//fun[1] = static_cast<funcptr> (&fun2);//error C2440: "static_cast": Cannot convert from "int (__cdecl *) (int)" to "Funcptr"fun[1] = reinterpret_cast<funcptr> (&fun2);//convert int fun to void fun with cast saveFUNCPTR2* Pfun = reinterpret_cast<funcptr2*> (&fun[1]);//switch back when you need to use it.printf ("Run Pfun =%d\n", (*pfun) ());//print get "Run Pfun =10"System ("Pause"); return 0;}

The new C + + type conversion is known

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.