I personally do not agree with the last sentence of the author. defined as a const member function, this function allows the caller to call it safely without changing the value of any member variable.
Turn: http://www.cnblogs.com/xuzhichuang/archive/2010/09/07/1820984.html
I mentioned a const function when I was watching the C ++ video tutorial a few days ago. I personally think the const function is simply a member who cannot modify the class in the function body, there is no such statement in C #. Record it here! The C ++ code will be written later. Any function that does not need to modify the class member should be defined as a const function as much as possible! For example, when getting the value of the member variable, this can also avoid bugs as much as possible, and it cannot pass during compilation!
In addition, the const function cannot call non-const functions, that is, it cannot be used to call a non-const function without modifying the value of the member variable! For example, the following code compilation fails:
Code
# Include <iostream>
Using namespace STD;
Class studentinfo
{
Public:
Void setscore (INT score) {This-> score = score ;}
Int getscore () const {printscore (); Return score ;}
Void printscore () {cout <score <Endl ;}
PRIVATE:
Int score;
};
Int main (void)
{
Return-1;
}
What should I do if I have to modify the member variables in the const member function? There are two main methods to check online:
1. implement forced type conversion using this pointer
This method is similar to the following:
Int getscore () const
{
(Const_cast <studentinfo *> (this)-> score + = 1;
Return score;
}
2. Define member variables as mutable
Similar to the following:
Mutable int score;
The above code tells the compiler member variable R to modify its value in the const function!
In fact, since we have defined the function as const, there is no need to modify the value of the member variable in the function body. Otherwise, the meaning of the const function will be lost, so there is no need to define it as a const function! Personal opinion!