C++ constant member function

Constant object : For example, if you set a class Demo, then const Demo Obj;//Defines that Obj is a constant object. In this way, the value of this object will not be changed

Constant member function :
1. Definition
The const keyword can be added after the member function description of the class, then the member function is a constant member function.
2. Declaration

class Sample
{
    
    
    public:
        int value;
        void GetValue() const;
        void func(){
    
    };
        Sample(){
    
    }

};

A const member function should not modify the object it acts on during execution. Therefore, the value of member variables cannot be modified in a constant member function (except for static member variables), nor can the same non-constant member function be called (except for static member functions).
Constant objects, and references or pointers to constant objects can only call constant member functions.

Guess you like

Origin blog.csdn.net/Algabeno/article/details/123603645