mutable关键字
在C++中,mutable 是为了突破 const 的限制而设置的。可以用来修饰一个类的成员变量。被 mutable 修饰的变量,将永远处于可变的状态,即使是 const 函数中也可以改变这个变量的值。
#include<bits/stdc++.h>
using namespace std;
class Test{
public:
Test();
int value() const;
private:
mutable int v;
};
Test::Test(){
v=1;
}
int Test::value() const{
v++;
return v;
}
int main(){
Test A;
printf("%d", A.value());
return 0;
}
即使A变量被声明 const 类型时 A.v 还是可以改变的。比如下面的代码。
#include<bits/stdc++.h>
using namespace std;
class Test{
public:
Test();
int value() const;
private:
mutable int v;
};
Test::Test(){
v=1;
}
int Test::value() const{
v++;
return v;
}
int main(){
const Test A;
printf("%d", A.value());
return 0;
}
原创不易
转载请标明出处
如果对你有所帮助 别忘啦点赞支持哈