C ++可变关键字?
可变数据成员是即使对象为常量类型,其值也可以在运行时更改的成员。它与常量相反。
有时逻辑只需要使用一个或两个数据成员作为变量,而另一个则作为常量来处理数据。在这种情况下,可变性是管理类的非常有用的概念。
示例
#include <iostream>
using namespace std;
code
class Test {
public:
int a;
mutable int b;
Test(int x=0, int y=0) {
a=x;
b=y;
}
void seta(int x=0) {
a = x;
}
void setb(int y=0) {
b = y;
}
void disp() {
cout<<endl<<"a: "<<a<<" b: "<<b<<endl;
}
};
int main() {
const Test t(10,20);
cout<<t.a<<" "<<t.b<<"\n";
// t.a=30; //Error occurs because a can not be changed, because object is constant.
t.b=100; //b still can be changed, because b is mutable.
cout<<t.a<<" "<<t.b<<"\n";
return 0;
}