I. Const Basics
If the const keyword does not involve pointers, we can understand it very well. The following is a case involving pointers:
Int B = 500;
Const int * A = & B; [1]
Int const * A = & B; [2]
Int * const A = & B; [3]
Const int * const A = & B; [4]
If you can differentiate the above four situations, congratulations! you have taken a great step. I don't know. It doesn't matter. We can refer to the practice on item21 in Objective C ++,
If the const is on the left side of the asterisk, the const is used to modify the variable pointed to by the pointer, that is, the pointer points to a constant;
If const is on the right side of the asterisk, const modifies the pointer itself, that is, the pointer itself is a constant.
Therefore, [1] is the same as [2], and the content pointed to by the pointer is a constant (The position of the const in the variable declaration is irrelevant ), in this case, you cannot change the content, for example, * A = 3;
[3] The pointer itself is a constant, and the content pointed to by the pointer is not a constant. In this case, the pointer itself cannot be changed, for example, a ++ is wrong;
[4] indicates that the pointer itself and the content pointing to are constants.
2. As a parameter
Void display (const double & R); or void display (const double * R );
Note:
1. It is meaningful to use the const limit when referencing or pointer parameters, but it does not make sense to use the const for values transmitted parameters.
2. Ensure that the value of the referenced variable is not changed.
3. Const has the same meaning before or after double, but different people write differently.
3. Const object
Objects declared as const can only be member functions declared as const In the struct class, and other member functions cannot be called.
Four const member functions
Type specifier function name (parameter table) const; void print (int I) const;
Note:
1 const is an integral part of the function type. Therefore, the const keyword must be included in the implementation part.
2. A common member function cannot update the data member of an object or call a member function without const modification in this class.
5. Const suggestions
1. Be bold in using const, which will bring you endless benefits, but the premise is that you must understand the original principles;
2. Avoid the most common assignment errors. For example, assign values to the const variable;
3. When using const in parameters, you should use references or pointers instead of common object instances, for the same reason as above;
4. Const should be well used in three member functions (parameters, return values, and functions;
5. Do not set the function return value type to const easily;
6 except for the overload operator, do not set the return value type as a const reference to an object;