#include <iostream> using namespace std; class Test { public: int x; int y; void const_m1() const; void const_m2() const; void m3(); void m4(); }; /** * //1常成员函数不能修改成员变量的值 * //2常成员函数只能调用常成员函数,不能调用普通成员函数 * //3普通成员函数可以调用常成员函数 */ void Test::const_m1(void)const { cout<<"start of const_m1() ,call:"<<endl; this->const_m2();//可以调用const_m2() //this->m3();//error C2662: “Test::m3”: 不能将“this”指针从“const Test”转换为“Test &” //this->m4();//error C2662: “Test::m4”: 不能将“this”指针从“const Test”转换为“Test &” //this->x = 3;//error C3490: 由于正在通过常量对象访问“x”,因此无法对其进行修改 cout<<"end of const_m1()"<<endl; } void Test::const_m2(void)const { cout<<"this is const_m2()"<<endl; } void Test::m3(void) { cout<<"this is m3(),call:"<<endl; this->const_m2(); cout<<"end of m3()"<<endl; } void Test::m4(void) { cout<<"this is m4()"<<endl; this->x = 3; } int main(void) { Test demo; demo.const_m1(); demo.const_m2(); demo.m3(); demo.m4(); while(1); return 0; }
/*测试结果:
start of const_m1() ,call:
this is const_m2()
end of const_m1()
this is const_m2()
this is m3(),call:
this is const_m2()
end of m3()
this is m4()
*/
时间: 2024-10-06 00:07:42