In C language, some forced type conversions are often seen, mainly in front of variable names (types). In C + +, there are some differences with C language, there are four types of forced type conversion in C + +.
Static_cast Its main transformation is the conversion between the relevant types
int main ()
{
float a = 1.2;
int B = static_cast<int> (a);
cout << b << Endl;
GetChar ();
return 0;
}
2.reinterpret_cast Its main transformation is the conversion between unrelated types
int main ()
{
int a = 1;
int *p = &a;
int b = reinterpret_cast<int> (p);
cout << b << Endl;
GetChar ();
return 0;
}
3.const_cast is a variable that unlocks the const type so that it can change the value of the variable
int main ()
{
volatile const int a = 1;
int *p = Const_cast<int *> (&a);
*p = 2;
cout << a << Endl;
GetChar ();
return 0;
}
4.dynamic_cast is a dynamic transformation, it mainly functions: 1. Can only be used for classes containing virtual functions 2. First check whether the conversion is successful, if the conversion is successful, if not return 0
Class A
{
Public
int _a;
virtual void Show ()
{}
};
Class B:p ublic A
{
Public
int _b;
};
void Test ()
{
A;
b b;
B *PB =dynamic_cast<b *> (&a);
cout << PB << Endl;
}
int main ()
{
Test ();
GetChar ();
return 0;
}
Some forced type conversions in C + +