常函数:

  • 成员函数后加 const 后 , 我们称这个为 常函数
  • 常函数内不可以修改成员属性
  • 成员属性声明加 关键词: “ mutable “之后 , 就可以在成员函数中修改属性

常对象:

  • 声明对象前加 const 为常对象
  • 常对象只能调动常函数

  1. Student{
  2. int age;
  3. mutable int height;
  4. void setAge(int a) const{
  5. age = a; //false; 常函数的属性不能修改
  6. height = a; //true
  7. }
  8. void getAge(){};
  9. }
  10. int main(){
  11. const Student stu;
  12. stu.setAge(10); //true
  13. stu.getAge(); //false; 常对象只能调用常函数
  14. }