In C + +, the Const object can only invoke the const member function, for what reason. Let's look at the following examples and analyze them to understand why:
#include <iostream>
#include <string>
using namespace std;
Class myint{
private:
int i;
Public:
MyInt () {
}
MyInt (int i): I (i) {
}
myint& operator++ () {
this->i = 1;
return *this;
}
Const MYINT operator++ (int) {
MyInt oldint = MyInt (*this);
This->i + 1;
return oldint;
}
void Show () {
cout << i << endl;
}
};
int main () {
MyInt mi (mi2);
Mi2++.show ();
return 0;
}
Compile an error:
We can see that the compiler complains that the Const Myint cannot be converted to Myint&, and that there are some conversion problems when the Const object calls the non-const member function, so let's take a look at the following analysis: The const object cannot invoke a non-const member function:
Void Show () is equivalent to void show (myint* this), not a const object that mi2 call is mi2.show (), That is, a non-const object is passed the pointer that myint* this entry, so the show function executes successfully.
What about the const object? const MYINT MI3 (10), now equivalent to the type of argument currently passed in is a const myint*, at which point passing the pointer to the myint* has a conversion failure problem. Therefore, a const member object cannot invoke a non-Const member object. The const object can call the const member function: The
Const object can invoke the const member function because the const member function default argument is const myint* This, we create a const object, that is, the pointer passed in is still a const myint*, so the call succeeds.