[C++ basic knowledge] constant member function, often quoted

const modified class member function-constant member function

The const-modified class member function is called a const member function, and the const-modified class member function actually modifies the this pointer implied by the member function. The effect is that no member of the class can be modified in the member function.

Format: Type specifier function name (parameter list) const;
For example: void showDate() const;

Explanation:
1. Constant member functions can access constant data members and ordinary data members. Constant data members can be accessed by regular member functions, and can also be accessed by ordinary member functions.
2. If an object is described as a constant object, only its constant member functions can be called through the object, but ordinary member functions cannot be called. Constant member function is the only external interface of constant object.
3. Constant member functions cannot update the data members of the object, nor can they exchange common member functions in the class, ensuring that the value of data members will never be updated in the constant member functions.

Often quoted

Format: const type & reference name;
for example: int a=1; const int &b=a;
where b is a constant reference, and the object it refers to is not allowed to be changed. If b=12; appears, it is illegal.
In practical applications, frequent references are often used as formal parameters of functions, and such parameters become constant parameters.

Comparison of access characteristics between regular member functions and ordinary member functions

Data member Ordinary member function Constant member function
Ordinary data member Can be accessed, can also change the value Can be accessed, but cannot change the value
Constant data member Can be accessed, but cannot change the value Can be accessed, but cannot change the value
Regular object Can't access, can't change the value Can be accessed, but cannot change the value

Guess you like

Origin blog.csdn.net/weixin_43962381/article/details/114294036