- Const_cast <new_type> (expression)
- Static_cast <new_type> (expression)
- Reinterpret_cast <new_type> (expression)
- dynamic_cast <new_type> (expression)
They have the same structure and look like a template method. These methods are provided to developers to use for pointers and reference conversions.
1. Const_cast Usage
Const_cast is a C + + operator that is primarily used to remove the const and volatile attributes in a composite type (no real removal).
The Const property of the variable itself cannot be removed, and to modify the value of the variable, it is generally to remove the const attribute of the pointer (or reference) and then modify it indirectly.
Usage:const_cast<type> (expression)
With the const_cast operator, you can only convert the const type* to type* and convert the const type& to type&.
This means that the source and destination types are identical except for the const attribute.
#include <iostream>using namespacestd;voidConstTest1 () {Const intA =5; int*p; P= const_cast<int*> (&a); (*P) + +; cout<<a<<Endl; cout<<*p<<Endl; }voidConstTest2 () {inti; cout<<"Please input a integer:"; CIN>>i; Const intA =i; int&r = const_cast<int&>(a); R++; cout<<a<<Endl;}intMain () {ConstTest1 (); ConstTest2 (); return 0;} Output:56Output 8 If input 7
Explain why output 8:
When the constant variable is a const int J =i, the compiler cannot optimize the direct output J, that is, I can not be used directly instead of J;
When the constant variable is const int j = 5 o'clock, when the direct output J, the compiler will be optimized, that is, the literal constant 5 directly instead of J;
C + + provides four conversion operators