What does the const modifier mean by converting an object into a constant object?
This means that the value of the variable modified using const cannot be modified at any position of the program, just like a constant!
The usage is as follows:
Const int a = 1; // a const constant variable a of the int type is defined here;
However, for pointers, const still works. Pay attention to the following two points because the following two problems are easy to confuse!
Let's take a look at the following example:
// Program Author: Guan Ning
// Site: www.cndev-lab.com
// All the manuscripts are copyrighted. If you want to reprint them, be sure to use the famous source and author.
# Include <iostream>
Using namespace std;
Void main (void)
{
Const int a = 10;
Int B = 20;
Const int * pi;
Pi = &;
Cout <* pi <"|" <a <endl;
Pi = & B;
Cout <* pi <"|" <B <endl;
Cin. get ();
}
The most important sentence in the above Code is const int * pi.
This sentence reads from the right base: pi is a pointer to an int type object defined as const;
The role of such a declaration method isModifiablePi pointerMemory AddressHoweverCannot be modifiedThe value pointing to the object..
If you add * pi = 10 after the code, this assignment operation is not allowed to be compiled!
Well, after reading the two examples above, you have a basic understanding of const, so let's look at a very confusing usage next!
See the following code.
// Program Author: Guan Ning
// Site: www.cndev-lab.com
// All the manuscripts are copyrighted. If you want to reprint them, be sure to use the famous source and author.
# Include <iostream>
Using namespace std;
Void main (void)
{
Int a = 10;
Const int * const pi = &;
Cout <* pi <"|" <a <endl;
Cin. get ();
}
The most important sentence in the above Code is const int * const pi
This sentence is read from the right: pi is a const pointer pointing to an int type object;
The role of such a declaration is youYou cannot modify the memory address of the object to which the pi points.AlsoThe value of an object cannot be modified using the pointer's unreferencing method, that is, using * pi = 10.;
Therefore, if you add * pi = 20 at the end, trying to modify the value of object a in this way is not allowed to be compiled!
Therefore, based on the above two points, after the code is modified to the following form, the value of object a or the address of the pointer pi can be modified somewhere in the program,The following method is often used as a parameter in the form of meaning, which ensures that the object will not be changed within the meaning!
// Program Author: Guan Ning
// Site: www.cndev-lab.com
// All the manuscripts are copyrighted. If you want to reprint them, be sure to use the famous source and author.
# Include <iostream>
Using namespace std;
Void main (void)
{
Const int a = 10; // This sentence is different from the above one. Please note!
Const int * const pi = &;
Cout <* pi <"|" <a <endl;
Cin. get ();
}