简单来说就是为了让类内的const函数可以修改成员变量
我们都知道,类内的const函数不能修改成员变量的值,然而开发过程中往往遇到需要计数或者其他需要变更变量的情况,此时mutable的作用就出现了,它能够让const函数修改被mutable的变量,编译器不会编译报错,例子如下
class student
{
void show () const;
}
void student :: show() const
{
cout << "no thing" << endl;
}
int main()
{
student s1;
s1.show();
}
定义一个student对象,然后调用了show方法,show方法只是打印输出,并没有修改任何变量,所以可以声明为const,开发过程中如果需要记录打印次数,此时但是const并不能修改打印次数变量,此时可以使用mutable
class student
{
public:
void show () const;
mutable int count;
}
void student :: show() const
{
cout << "no thing" << endl;
count ++
cout << count << endl;
}
int main()
{
student s1;
s1.show();
}
以上只是一个简单示例,如果需要运行,可以继续补充