Const修饰成员函数
在成员函数后面加const,const修饰this指针所指向的对象,也就是保证调用这个const成员函数的对象在函数内不会被改变。
class Date { public: void Display() { cout << this->_year << "-" << this->_month << "-" << this->_day << endl; } private: int _year; int _month; int _day; }; int main() { Date d1; const Date d2; d1.Display(); d2.Display(); return 0; }
对于上面的程序,d1调用Display(Date* this),&d1为Date*类型。而&d2的类型是const Date*。d2的内容不能被修改,Date*类型可以被修改,类型不匹配,因此调用d2会出错。
要调用const类型的d2,就要让成员函数被const修饰。
void Display1()const { cout << this->_year << "-" << this->_month << "-" << this->_day << endl; }
该函数可以同时被d1,d2调用。d1可以被修改,在被Display()const调用时权限被缩小,不能在该函数内部被修改。由于Display() 和Display1()const 是两种类型,因此可以同时存在。
对于const对象和非const成员函数,有下面几种情况:
1)const对象可以调用const成员函数;
2)非const对象可以调用非const成员函数;
3)Const对象不可以调用非const成员函数;例如:d2.Display();
4)非const对象可以调用const成员函数;d1.Display1();
对于const成员函数与其他const成员函数非const成员函数,有以下几种关系:
class AA { public: void fun1() { fun2();//this->fun2(); this->fun1();//情况2 } void fun2(){ } private: int a; }; class AA { public: void fun1() { fun2();//情况4 this->fun1(); } void fun2()const { fun1();//情况3,错误 fun2();//情况1 } private: int a; };
1)const成员函数可以调用const成员函数;
2)非const成员函数可以调用非const成员函数;
3)const成员函数不可以调用非const成员函数;
4)非const成员函数可以调用const成员函数;