The C ++ function is followed by the const modifier and the const modifier.
When declaring a member function, the const keyword is used to indicate that this function is a read-only function. That is to say, this function will not modify any data member (object ). To declare a const member function, place the const keyword behind the function brackets. The const keyword should be included in the declaration and definition.
Any function that does not modify data members should be declared as the const type. If the const member function is accidentally modified or other non-const member functions are called, the compiler will point out an error, which will undoubtedly improve the robustness of the program.
# Include <iostream> using namespace std; class temp {public: temp (int age); int getAge () const; void setNum (int num); private: int age ;}; temp: temp (int age) {this-> age = age;} int temp: getAge () const {age + = 10; // # Error... error C2166: l-value specifies const object # return age;} void main () {temp a (22); cout <"age =" <. getAge () <endl ;}
Because the const function is declared, no data member can be modified, but 10 is added to the age data member, so an error is generated.