when const encounters a pointer
In general, the const modifier pointers can be divided into the following concentration cases.
Describe |
Example |
Meaning |
Note |
Const on the left of * |
const INT *b=&a; int const *b=&a; |
The const modifier pointer points to a variable, which means that we cannot modify the pointer B by Point to the value to modify a. that is, *b=100; This operation is wrong. At this point, pointer B itself is not a constant, *b is a constant. |
In this case, if you want to modify the value returned by the *b, it is possible to modify the object referred to by pointer B in two ways: · Change the value of the variable A that the B points to, a=100; • Let b point to another variable, int c=100; b=&c; |
Const on the right of * |
int* Const b=&a; |
The const modifier pointer, which means that attempting to change the value of B is wrong. Such as: b++; ++b, such operations are all wrong. At this point, pointer b itself is a constant, *b is not a constant. |
Since pointer b is a constant, it must be initialized when she is created, or it will go wrong. |
* The left and right sides have a const |
Const int* Const b=&a; |
Both the pointer itself and the contents of the pointer are constants. |
|
To put it another point, when C + + defines a class, if there is a function inside the class we want it to not modify the member variables inside the class, and after the parameter list of the function a const can tell the compiler that the function does not modify the member variables inside the class. But you want the function to have this effect on only a subset of member variables, and you can modify the member variable in the const function by adding a mutable to the member variable that you can modify.
C + + const modifier pointers