C ++ const member functions
First fact:
In a certain type, two functions can be declared and defined in this way, and can be overloaded)
void pa(){ cout<<"a"<<endl;}void pa() const{ cout<<"b"<<endl;}
The above statement is correct.
Based on this fact, I thought about its mechanism.
Experiments show that,
The second fact:
A common function (not a member function of a class) can be overloaded as follows ):
void fun(const int &a){ cout<<a<<endl;}void fun(int &a){ cout<<a<<endl;}
The second fact shows that if the function parameter is of the [Reference Type], [const] and [without const] can be reloaded.
Third fact:
A common function (not a member function of a class) can also be overloaded using a pointer like this ):
void test(const int* a){ cout<<*a<<endl;}void test(int* a){ cout<<*a<<endl;}
The third fact shows that the pointer can also be reloaded by adding const and without const.
Analyze the first fact:
According to c ++ primer, a member function itself has an implicit parameter: ClassName * const this // this parameter is irrelevant to the topic of this article.
But let's explain this const first. That is to say, a pointer itself can no longer point to others but to itself.
Therefore, you cannot change the value of this in the class,
This = 0; // error!
Let's talk about these two class member functions:
void pa();void pa() const;
It can be fully written and become a pseudo-code that is easy to understand, like this:
void pa(ClassName *const this);void pa(const ClassName *const this);
First, I have already said this.
The second is a special syntax provided by c ++ to the user, that is, the member function adds const, which is actually added to the front of the implicit parameter this.
Okay. Summary:
This is why member functions can be overloaded by adding the const modifier.