#include<iostream>
#include<string>
using namespace std;

class Person {
public:
    void showage() {
        age = 7;
        cout << age << endl;
    }



    //成员函数后加const,我们称它为常函数
    //常函数内部可以修改成员属性
    //成员属性前面加 mutable关键字后,在常函数中依然可以修改
    void showheight()const {    
        this->age = 100; //如果age的属性修饰前面没有加mutable,那么这里就会报错
        //因为这是一个常函数,常函数其实就是将this常量指针修改为了常量指针常量.
        //靠 mutable修饰了成员属性后,你才能修改一个指针常量
    }


    mutable int age;
    int height;

};
int main() {
    Person p;
    p.showage();

    Person const p1; //申明一个常对象
    //p1.showage();  //错误,常对象只能调用常函数.

}

最后修改:2022 年 12 月 05 日
如果觉得我的文章对你有用,请随意赞赏