常函数:
- 成员函数后加const称之为常函数
- 常函数不可以修改成员属性
- 成员属性声明时加上关键字mutable后,在常函数中依旧可以修改
常对象:
- 声明对象前加const称该对象为常对象
- 常对象只能调用常函数
#includeusing namespace std; #include //常函数 class person { public: //this指针的本质是指针常量,指针的指向是不可以修改的 //this指针指向的值可以修改 //person * const this; //在成员函数后面加const,修饰的是this指针,指针指向的值也没法该 void showPerson() const //相当于const person * const this; { m_B = 100; //m_A = 100; } int m_A; mutable int m_B; //特殊对象,在常函数中也可以修改这个值 }; int main() { cout << "程序运行结束" << endl; system("pause"); return 0; }
#includeusing namespace std; #include //常函数 class person { public: //this指针的本质是指针常量,指针的指向是不可以修改的 //this指针指向的值可以修改 //person * const this; //在成员函数后面加const,修饰的是this指针,指针指向的值也没法该 void showPerson() const //相当于const person * const this; { m_B = 100; //m_A = 100; } void func() { } int m_A; mutable int m_B; //特殊对象,在常函数中也可以修改这个值 }; void test02() { const person p1; //p1.m_A = 100; p1.m_B = 100;//特殊值,在常对象中也可以修改这个值 //常对象只能调用常函数 p1.showPerson(); //p1.func();常对象不能调用普通成员函数 } int main() { cout << "程序运行结束" << endl; system("pause"); return 0; }



