Four types of conversion operators are defined in C + +: static_cast, const_cast, dynamic_cast, and reinterpret_cast.
The usage of static_cast is similar to the coercion type conversion in C, which can convert one type to another type:
Double N;int a=static_cast<int> (n);
Const_cast is used to remove the constant property of a variable and convert a const variable to a non-const variable:
const int A=0;int b=const_cast<int> (a);
Dynamic_cast is used to "transform the pointers or references that point to base class objects into derived or objects that point to pointers class references and know if the transformation was successful." "If the transformation fails, it appears as a null pointer (when the transformed object is a pointer) or a exception (when the transformed object is reference).
Widget *pw;update (dynamic_cast<specialwidget*> (PW)), void Updateviaref (specialwidget& rsw); Updateviaref ( Dynamic_cast<specialwidget&> (*PW));
The conversion result of the reinterpret_cast operator is closely related to the compiler platform, which does not have portability. It can be used to convert pointer types:
typedef void (*MYFUN) (int); void fun1 (int a) {Std::cout<<a<<std::endl;} int fun2 (int a,int c) {Std::cout<<c<<std::endl;return A;} int main () {void (*fun) (int);fun=reinterpret_cast<myfun> (fun2); fun (5); System ("pause"); return 0;}
Because this operator is not portable, in some cases such a transformation may result in incorrect results, so it is not necessary to avoid the function pointer transformation as much as possible.
About type conversions in C + +