const修饰的成员函数成为 常函数
- //const修饰成员函数
- class Person{
- public:
- Person(){
- this->mAge = 0;
- this->mID = 0;
- }
- //在函数括号后面加上const,修饰成员变量不可修改,除了mutable修饰的变量
- void sonmeOperate() const{
- //this->mAge = 200; //mAge不可修改
- this->mID = 10;//mID可以修改,因为在定义mID时前面加了mutable进行修饰
- }
- void ShowPerson(){
- cout << "ID:" << mID << " mAge:" << mAge << endl;
- }
- private:
- int mAge;
- mutable int mID;
- };
-
- int main(){
-
- Person person;
- person.sonmeOperate();
- person.ShowPerson();
-
- system("pause");
- return EXIT_SUCCESS;
- }
2. const修饰对象
const修饰的对象称之为 常对象
- class Person{
- public:
- Person(){
- this->mAge = 0;
- this->mID = 0;
- }
- void ChangePerson() const{
- mAge = 100;
- mID = 100;
- }
- void ShowPerson(){
- this->mAge = 1000;
- cout << "ID:" << this->mID << " Age:" << this->mAge << endl;
- }
-
- public:
- int mAge;
- mutable int mID;
- };
-
- void test(){
- const Person person;
- //1. 可访问数据成员
- cout << "Age:" << person.mAge << endl;
- //person.mAge = 300; //不可修改
- person.mID = 1001; //但是可以修改mutable修饰的成员变量
- //2. 只能访问const修饰的函数
- //person.ShowPerson();
- person.ChangePerson();
- }