여기서 우리는 C++에서 mutable 키워드가 무엇인지 볼 것입니다. mutable은 C++의 스토리지 클래스 중 하나입니다. 가변 데이터 멤버는 항상 변경할 수 있는 그런 종류의 멤버입니다. 객체가 const 유형인 경우에도 마찬가지입니다. 하나의 멤버만 변수로, 다른 멤버는 상수로 필요하면 변경 가능하게 만들 수 있습니다. 아이디어를 얻기 위해 한 가지 예를 살펴보겠습니다.
예시
#include <iostream>
using namespace std;
class MyClass{
int x;
mutable int y;
public:
MyClass(int x=0, int y=0){
this->x = x;
this->y = y;
}
void setx(int x=0){
this->x = x;
}
void sety(int y=0) const { //member function is constant, but data will be changed
this->y = y;
}
void display() const{
cout<<endl<<"(x: "<<x<<" y: "<<y << ")"<<endl;
}
};
int main(){
const MyClass s(15,25); // A const object
cout<<endl <<"Before Change: ";
s.display();
s.setx(150);
s.sety(250);
cout<<endl<<"After Change: ";
s.display();
} 출력
[Error] passing 'const MyClass' as 'this' argument of 'void MyClass::setx(int)' discards qualifiers [-fpermissive]
줄을 제거하여 프로그램을 실행하면 [ s.setx(150); ], 그리고 -
출력
Before Change: (x: 15 y: 25) After Change: (x: 15 y: 250)