C + + Programming Method 3: Forcing type conversions

Source: Internet
Author: User

Coercion type conversion (display transformation)

Dynamic_cast<dst_type> (Src_var)

Src_var must be a reference or pointer type, the Dst_type class contains virtual functions, otherwise there will be compile errors;

If there is no inheritance relationship between the target class and the source class, the conversion fails and returns a null pointer (note: Failure is not a running crash)

Static_cast<dst_type> (Src_var)

A base class object cannot be converted to a derived class object, but a base-class pointer can be converted to a pointer to a derived class

Derived class objects (pointers) can be converted to objects (pointers) of the base class

Between classes that do not have an inheritance relationship, you must have a conversion path to convert (either custom or language syntax support)

#include <iostream>using namespacestd;classb{ Public:    Virtual voidf () {}};classB | PublicB {};classE {};intMain () {D D1;    B B1; //D1 = static_cast<d> (B1);//error: Cannot convert from base class back to derived classB1 = static_cast<b>(D1); //B1 = dynamic_cast<b> (D1);//error: The converted must be a pointer or referenceb* PB1 =NewB (); D* PD1 = static_cast<d*>(PB1); if(PD1) cout<<"OK"<< Endl;//the base class pointer can be converted to a pointer of a derived classPD1 = dynamic_cast<d*>(PB1); if(PD1) cout<<"OK"<< Endl;//A base class cannot be dynamically converted to a derived classD* PD2 =NewD (); B* PB2 = static_cast<b*>(PD2); if(PB2) cout<<"OK"<< Endl;//OKPB2 = dynamic_cast<b*>(PD2); if(PB2) cout<<"OK"<< Endl;//OKE* PE = dynamic_cast<e*>(PB1); if(!PE) cout<<"OK"<< Endl;//OK//PE = static_cast<e*> (PB1);//error: No inheritance relationship cannot be converted//e e = static_cast<e> (B1);//error: No way to provide conversions    return 0;}

C + + Programming Method 3: Forcing 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.