需要注意的是:mutable不能修饰const 和 static 类型的变量。
#include <iostream> using namespace std; class Person{ public: Person(); ~Person(); int getAge() const; int getCallingTimes() const; private: int age; // 不希望对age 该表 char* name; float score; mutable int m_nums; // 希望对m_nums改变 }; Person::Person() { m_nums = 0; } Person::~Person() {} int Person::getAge() const { std::cout<< "calling the method" << std::endl; m_nums ++; return age; } int Person::getCallingTimes() const { return m_nums; } int main(int argc, char *argv[]) { Person *person = new Person(); for(int i = 0;i< 10;i++) { person->getAge(); } std::cout << "getAge()方法被调用了" <<person->getCallingTimes()<<"次" << std::endl; return 0; }