当在c++中,定义类时,对一个函数使用const进行修饰后,该函数将无法修改类成员变量的值,但对mutable修饰的成员变量没有这个限制。
class foo{ private: mutable int f; public: void setf(int a) const; void print() const; }; void foo::setf(int a) const{ f = a; } void foo::print() const{ cout<<f<<endl; } int main(){ foo fo; fo.setf(1); fo.print(); }
对于类内f成员变量的定义,如果没有mutable修饰,在const修饰的setf()成员函数修改f是不可编译的。如果加上mutable修饰f后,编译通过,且运行正常。