When declaring a member function, the const keyword is used to indicate that the function is a "read-only (read-only)" function, which means that the function does not modify any data member (object). To declare a const member function, place the const keyword after the function bracket. The const keyword should be placed when declaring and defining.
Any function that does not modify a data member should be declared as a const type. If you inadvertently modify the data member when you write the const member function, or if you call other non-const member functions, the compiler will indicate the error, which will undoubtedly improve the robustness of the program.
#include <iostream>using namespacestd;classtemp{ Public: Temp (intAge ); intGetage ()Const; voidSetnum (intnum);Private: intAge ;}; Temp::temp (intAge ) { This->age =Age ;}intTemp::getage ()Const{ Age+=Ten;//#Error ... Error c2166:l-value specifies const object # returnAge ;}voidMain () {Temp A ( A); cout<<"age="<< a.getage () <<Endl;}
Because the const function is declared, no data member can be modified, but here the age data member is added 10, resulting in an error.
const modifier after C + + function