mutable的使用

需要注意的是: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;
}

 

posted @ 2021-03-17 13:15  countryboy666  阅读(106)  评论(0编辑  收藏  举报