Code:
1#include <iostream>2 3 using namespacestd;4 5 classa{6 Public:7 voidfunc1 () {8cout<<"func1"<<Endl;9 }Ten voidFunc1 ()Const{ Onecout<<"Const FUNC1"<<Endl; A } - voidFunc2 ()Const{ -cout<<"Const FUNC2"<<Endl; the } - voidfunc3 () { -cout<<"func3"<<Endl; - } + }; - + intMain () { A at A A1; - a1.func1 (); - A1.func2 (); - -AConstA2; - a2.func1 (); in //a2.func3 (); Compile error - to return 0; +}
Output:
Func1const Func2const func1
Analysis:
1. A regular object can only invoke the constant member function.
2. Normal objects can call all member functions.
3. When a member function is called on an object, the compiler assigns the address of the object to the this pointer, and then calls the member function, which is implicitly used by the this pointer each time the member function accesses the data member.
4. When a member function is called, it is automatically passed an implied argument, which is a pointer to the object where the member function resides.
5. In C + +, the This pointer is implicitly declared as: X *const This, which means that the this pointer cannot be assigned a value;
In the const member function of the X class, the type of the this pointer is: const x* const, which indicates that the object pointed to by this pointer is non-modifiable (that is, the data member of such an object cannot be assigned to a value operation);
6. Because this is not a regular variable, the address of this cannot be obtained.
A more detailed explanation: http://blog.csdn.net/zhuyingqingfen/article/details/31751111
It is important to note that the constant member function cannot modify the object's member variables.
The constant member function in C + +