A const member function, which can read the data members of a class, but cannot modify the data members of the class.
1 statement
After the parameter list declared by the member function, add the CONST keyword, declare it as a constant member function (const member function), indicating that it is not allowed to modify the data member of the class
The following defines a date class that represents dates in the form of year, month, and day, respectively.
classDate { Public: intDay ()Const{returnD;} intMonth ()Const{returnm;} intYear ()Const; voidAdd_year (intn);//Add n YearsPrivate: intD, M, Y;};
1) If the constant member function attempts to modify the data member of the class, the compiler will error
// error:attempt to change member value in const function int Const { return + +y;}
2) When defining a constant member function outside the class, the const keyword cannot be omitted
// Error:const Missing in member function type int date::year () { return y;}
2 calls
A constant member function, which can be called by the const and Non-const class objects, and the Non-const member function can only be called by the Non-const type class object.
void Const date& CD) { int i = d.year (); // OK D.add_year (1); // OK int j = cd.year (); // OK Cd.add_year (1); // Error}
3 this pointer
In <c++ primer>, there is a more detailed explanation of the const suffix:
The this pointer defaults to a const-type pointer to the Non-const class object, so the this pointer cannot be bound to a Const class object, that is, the Const class object cannot invoke the class's member function.
A const suffix is appended to the argument list of the member function declaration, indicating that its this pointer is pointing to the Const class object, so that the Const class object can invoke the constant member function.
Summary:
1) A const suffix in a class member function declaration that indicates that its this pointer is pointing to a Const class object , so the Const class object can call a const member function (const member functions)
2) A member function that is declared as a constant member function if the data member only involves a read operation and does not modify the operation.
Resources:
<c++ Programming language_4th> CH 16.2.9.1
<c++ primer_5th> Ch 7.1.2
<effective c++_3rd> Item 3
C + + Const member function