"C + +" type conversions

Source: Internet
Author: User

    • Introduction

C + + style four types of conversion methods: Static_cast, dynamic_cast, reinterpret_cast, const_cast.

  Welcome to Lovickie's blog Http://www.cnblogs.com/lovickie

    • Static_cast

The use of static_cast allows for a near-c-style static conversion, but adds security considerations.

Double 3.14 ; int i = static_cast<int> (d);

  Welcome to Lovickie's blog Http://www.cnblogs.com/lovickie

    • dynamic_cast

The upstream conversion (subclass pointer to parent pointer) is generally secure and must, of course, be valid for public inheritance. The downstream conversion (the pointer to the parent pointer rotor class) is probably unsafe (for example, when the pointer is pointing to the parent class object).

You can use dynamic_cast<type> (expression) to dynamically transform the condition that the type is a pointer or reference, and the base class is polymorphic when the downstream conversion (there is a virtual function, so that a type information pointer can be placed in the virtual table--dynamic_cast A typical implementation of this model). For unsafe pointer downstream conversions, DYNAMIC_CAST returns NULL.

classDad {};classSon: Publicdad{ Public:    voidfunc ();};intMain () {Dad D; Son*S1 = (son*) &d;//compiled byS1->func ();//Run ErrorSon *s2 = static_cast<son*> (&d);//Compile Error: Unable to convertS2->func (); Son*S3 = dynamic_cast<son*> (&d);//Compile error: Dad is not a polymorphic type unless there is a virtual function in dad}
classdad{Virtual voidfunc ();};classSon: PublicDad {};intMain () {son son; Dad*PD = dynamic_cast<dad*> (&son);//upstream conversion, OKdad Dad; Son*ps = dynamic_cast<son*> (&dad);//downstream conversion, ps=0Dad*pdad =NewDad, *pson =NewSon; PS= Dynamic_cast<son*> (Pdad);//downstream conversion, ps=0PS = dynamic_cast<son*> (Pson);//downlink conversion, OK}

As shown in the example above, when the pointer is down, the dynamic_cast will return 0 if it fails, and the Bad_cast exception will be thrown if it fails to reference the downstream conversion.

void F (Dad &dad) {    try  {        &son = dynamic_cast<son&>  (dad);    }     Catch (bad_cast) {        //  exception handling     }}

Dynamic_cast is always considered safe when converting the source pointer or the target pointer to void *. The target pointer is void * which can be used to determine the starting address of an object of polymorphic type.

class a{    virtualvoid  func ();}; int Main () {    new  A;     void *v = dynamic_cast<void*> (a);  // also requires a polymorphic    A = dynamic_cast<a*> (v);}

As with typeID, dynamic_cast uses the runtime type information RTTI (run time types information), which may not be supported by some platforms.

  Welcome to Lovickie's blog Http://www.cnblogs.com/lovickie

    • Reinterpret_cast

You can use reinterpret_cast<type> (expression) to convert a type between pointers or between pointers and integers, as well as requiring the type to be a pointer or reference.

int New int ; long i = reinterpret_cast<long>0;  // p no longer points to new intp = reinterpret_cast<int*> i;  // P re-point to new int

  Welcome to Lovickie's blog Http://www.cnblogs.com/lovickie

    • Const_cast

You can use Const_cast to convert a constant to a variable, removing the const attribute.

Const Char " Hello " ; char *s = const_cast<char*> (str);

In the const member function of Class A, if you want to modify the member variable of a, you can first force the this to remove the Const property. But when the object itself is a constant, the result is unpredictable.

classa{BOOLm; Public:    voidFunc ()Const{A*a = const_cast<a*> ( This);//Force Removal of the const attributeA->m =true; }};intMain () {A A1; ConstA A2;  A1.func (); //OKA2.func ();//No defined behavior}

Therefore, a better solution to make certain member variables modifiable by the const member function is to declare member variables as mutable, or to encapsulate these member variables in a struct pointer.

  Welcome to Lovickie's blog Http://www.cnblogs.com/lovickie

    • Conclusion

No.

"C + +" type conversions

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.