#include <iostream>using namespacestd;classTest { Public: intx; inty; voidCONST_M1 ()Const; voidCONST_M2 ()Const; voidm3 (); voidM4 ();};/** *//1 member function cannot modify the value of a member variable *//2 constant member function can only call the regular member function, cannot call the ordinary member function *//3 Ordinary member function may call the constant member function*/voidTEST::CONST_M1 (void)Const{cout<<"start of CONST_M1 (), Call:"<<Endl; This->CONST_M2 ();//can call const_m2 ()//this->m3 ();//error C2662: "TEST::M3": Cannot convert "This" pointer from "Const test" to "Test & "//this->m4 ();//error C2662: "TEST::M4": Cannot convert "This" pointer from "Const test" to "Test & "//this->x = 3;//error C3490: cannot be modified because "X" is being accessed through a const objectcout<<"End of CONST_M1 ()"<<Endl;}voidTEST::CONST_M2 (void)Const{cout<<"This is const_m2 ()"<<Endl;}voidTEST::M3 (void) {cout<<"This was M3 (), Call:"<<Endl; This-const_m2 (); cout<<"End of M3 ()"<<Endl;}voidTEST::M4 (void) {cout<<"This is M4 ()"<<Endl; This->x =3;}intMainvoid) {Test demo; DEMO.CONST_M1 (); DEMO.CONST_M2 (); DEMO.M3 (); DEMO.M4 (); while(1); return 0;}
/* Test results:
Start of CONST_M1 (), Call:
This is const_m2 ()
End of CONST_M1 ()
This is const_m2 ()
This was M3 (), Call:
This is const_m2 ()
End of M3 ()
This is M4 ()
*/
C + +, common member functions