변경 가능한 데이터 멤버는 개체가 상수 유형인 경우에도 런타임에 값을 변경할 수 있는 멤버입니다. 상수와 정반대입니다.
때로는 하나 또는 두 개의 데이터 멤버만 변수로 사용하고 다른 하나는 데이터를 처리하는 상수로 사용하는 논리가 필요합니다. 그런 상황에서 가변성은 클래스를 관리하는 데 매우 유용한 개념입니다.
예시
#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;
}