C ++ learning const: Learning const
Const is often used in C ++. in programming, we recommend that you use const to tell the compiler and other programmers that a value should remain unchanged.
Const can be used in many places:
(1) constants used in the scope of global or namespace outside classes
(2) Modify objects declared as static in a file, function, or block Scope
(3) Modify static and non-static member variables in classes.
(4) For pointers, you can also point out that the pointer itself, the pointer refers to, or both are const, such:
1 char greeting[] = "Hello";2 char * p = greeting;3 const char * p = greeting;4 char * const p = greeting;5 const char * const p = greeting;
Although the const syntax is changeable, it is easy to understand:
(1) const appears on the left of the asterisk, indicating that the things are constants.
(2) const appears on the right of the asterisk, indicating that the pointer itself is a constant
(3) const appears on both sides of the asterisk, indicating that the things and pointers are constants.
Note: If the things are constants, the meaning of the keyword const is the same before the type and after the type and before the asterisk. For example:
1 void f1 (const Widget * pw); // f1 gets a pointer pointing to a constant Widget object 2 void f2 (Widget const * pw); // f2 is also
The most powerful usage of const is the application in the face of function declaration. In a function declaration, const can be associated with function return values, parameters, and functions. They also have some benefits:
(1) making the function return a constant value can often reduce accidents caused by customer errors, without giving up security and efficiency.
(2) const is implemented in member functions. The purpose is to confirm that the member function can act on the const object. This type of member functions is very important because:
A. They make the class interface easier to understand. It is important to know which function can change the object and which function cannot.
B. They make the "Operation const object" possible.