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