In fact, I have been familiar with Objective C ++ for a long time, but I have never used const.
Using const is a wonderful thing, because the compiler will help you tell a lot of things. It is of great help to improve the robustness of the program. Const actually changes the type, which limits the way objects can be used.
1. Define Constants
(1) const modifies variables. The following two definitions are essentially the same. It means that the variable of the const type is unchangeable.
Int const var;
Const int var;
2. Use CONST for pointers
(1) the pointer itself is a constant that is unchangeable.
Char * const pVar;
(2) The Pointer Points to a constant that is unchangeable.
Const char * pVar;
(3) Both are unchangeable.
Const char * const pVar;
(4) Difference Methods
If the const is on the left side of *, 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 *, const is to modify the pointer itself, that is, the pointer itself is a constant.
3. Use CONST in Functions
(1) const modifier function parameters
A. The content indicated by the parameter pointer is constant immutable
Void fun (const char * Var );
B. the parameter is a reference. To increase efficiency and prevent modification. When modifying referenced parameters:
Void fun (const Class & Var );
(2) const modifier function return value
The const modifier function does not actually return a lot of values. Its meaning is basically the same as that of the const modifier for common variables and pointers.
A. const int * fun () // const int * pValue = fun2 () when calling ();
// We can regard fun2 () as a variable, that is, the pointer content is immutable.
(3) const modifier member functions
If a const modifies a member function of a class, the member function cannot modify any non-const member function of the class. It is generally written at the end of the function.
Class
{
...
Void fun () const; // constant member function, which does not change the member variable of the object.
// You cannot call any non-const member functions in the class.
}
Examples commonly used in const
Template <class T>
T getSomeMember () const
{...}
Template <class T>
Const T * getMember () const
{...}
Template <class T>
Void setSomeMember (const T & Member)
{...}
Const T & Member
Template <class T>
T fun (const T * Member)
{...}
Const T * Member
Bool isMember () const
{...}
Template <class T>
Bool hasmember (const T & member) const
{...}