The const keyword can be used in a C + + class to declare a member function that does not modify an object, which you need to be aware of:
1. Const object can only be called by constants member function
2. A const object can call the function
Take the following code as an example to explain:
1 classperson{2 Public:3 voidprint () {4cout<<"I am a common function!"<<Endl;5 }6 voidShow ()Const{7cout<<"I am a const function!"<<Endl;8 } 9 };Ten intMain () { One ConstPerson A; A a.print (); -}
The result of the program compilation is:
[Error] passing ' const person ' as ' this ' argument of ' void Person::p rint () ' Discards qualifiers [-fpermissive]
It can be understood that when a member function is called on an object, the this pointer is passed in :
1, the common object calls the very member function error reason:
The Print function prototype is
Print (person *const a,int i); (pseudo code)
the invocation of the member function a.print () can be equivalent to:
Print (&a,1); (pseudo code)
that is , this is passed in as an implicit parameter, but The type of a pointer is const person *const;
This can be explained by the knowledge passed by the function parameter, that is, an argument: a constant pointer to a constant object, a parameter: a constant pointer to a normal object, and an argument mismatch (as can be seen from a compilation error).
2, the common object can call the usual member function reason:
the function prototypes of show can be considered as
Show (const person*const a,int i); (pseudo code)
that is , the const keyword modifies the incoming object pointer;
At this point, the formal parameter arguments are matched.
In short, this can be judged by the knowledge of the arguments passed.
C + + Class Const member functions