Type conversion has C-style, and of course, C + + style. C-style conversion format is very simple (type) EXPRESSION, but C-style type conversion has a lot of shortcomings, sometimes with C-style conversion is not appropriate, because it can be converted between any type, For example, you can convert a pointer to a const object into a pointer to a non-const object, convert a pointer to a base class object to a pointer to a derived class object, the difference between the two transformations is huge, but the traditional C-style type conversion does not differentiate between these exponentially. Another drawback is that C-style conversion is not easy to find, he consists of a parenthesis plus an identifier, and such things in the C + + program a lot. So C + + in order to overcome these shortcomings, the introduction of 4 new type conversion operators, they are 1.static_cast 2.const_cast 3.dynamic_cast 4.reinterpret_cast.
1.static_cast
The most commonly used type converter, in the normal state of the type conversion, such as converting int to float, such as: int i;float F; f= (float) i; or f=static_cast<float> (i);
2.const_cast
Used to remove the const attribute and change the const type pointer to a pointer of the non-const type, such as: const int *fun (int x,int y) {} int *ptr=const_cast<int *> (Fun (2.3))
Const int + ; Const int* const_p = &constant; int* modifier = const_cast<int*>(const_p); 7;
Const int + ; Const int* const_p = &constant; int* modifier = (int*) (const_p);
3.dynamic_cast
This operator is used by the runtime to check whether the transformation is type-safe, but only when the polymorphic type is valid, that is, the class has at least one virtual method. Dynamic_cast and static_cast have the same basic syntax, dynamic_cast is primarily used for upstream and downstream conversions between class hierarchies, and can also be used for cross-conversion between classes. The effect of dynamic_cast and static_cast is the same when upstream conversions are made between class hierarchies, and dynamic_cast has the function of type checking, which is more secure than static_cast when making a downstream conversion. Such as:
Class C
{
... c No Virtual functions
};
Class t{
...
}
int main ()
{
Dynamic_cast<t*> (new C);//Error
}
At this point it is legal to change to the following:
Class C
{
Public
virtual void m () {};//C is now polymorphic
}
4.reinterpret_cast
Interpret is an explanation, and reinterpret is a re-interpretation, meaning that the identifier is re-interpreted in the binary form of the data, but does not change its value. such as: int i; Char *ptr= "Hello freind!"; I=reinterpret_cast<int> (PTR); This conversion method is seldom used.
Four types of forced type conversions in C + +