Const object
If you want to define a class object that will never change, you can define a const object as follows:
Const cbox standard (10.0, 10.0, 10.0 );
The value of the member variable of the standard object will never change. To ensure that the const object does not change, the compiler cannot call non-const member functions of the const object. Even if this non-const member function does not change the value of any member variable.
The principle of a const object is to convert this pointer of an object into a pointer to a const object (the content pointed to by the pointer cannot be changed ). When calling the object's member function, there is an implicit this pointer parameter. The pointer to a const object cannot be implicitly converted to a pointer to a non-const object. The implicit this pointer parameter of a common member function is a pointer to a non-const object. Therefore, calling the member function of the const object will cause the compiler to try to convert the pointer to the const object to a non-const Object Pointer, which is not allowed. Therefore, compilation fails.
Const member functions
1. the const member function promises not to change the value of the member variable of the object. Therefore, changing the value of member variables is not allowed in the const member function. You cannot call non-const member functions of an object. You can only call the const member functions.
2. the const member functions must be declared and defined using the const keyword (if the definition and implementation are separate), followed by the arc brackets behind the function parameter list. As shown below:
class CBox{public:explicit CBox(double lv = 1.0,double bv = 1.0,double hv = 1.0){//...}double Volume() const;private:double m_Length;double m_Width;double m_Height;};double CBox::Volume() const{return m_Length*m_Height;}
Timely return values, function names and parameters are identical, and functions with and without const modifiers are different. (The const modifier is also part of the function signature ?). Therefore, you can define the const and non-const versions of the same function.
Suggestion: when defining a class, it is best to define all member functions that do not change to class member variables as const functions.