重複の可能性:
C++ 'mutable' キーワード
class student {
mutable int rno;
public:
student(int r) {
rno = r;
}
void getdata() const {
rno = 90;
}
};
重複の可能性:
C++ 'mutable' キーワード
class student {
mutable int rno;
public:
student(int r) {
rno = r;
}
void getdata() const {
rno = 90;
}
};
type のオブジェクトで使用されている場合でも、メンバー関数rno
を介してメンバーに書き込む (つまり、"mutate") ことができます。student
const
student
class A {
mutable int x;
int y;
public:
void f1() {
// "this" has type `A*`
x = 1; // okay
y = 1; // okay
}
void f2() const {
// "this" has type `A const*`
x = 1; // okay
y = 1; // illegal, because f2 is const
}
};
このmutable
キーワードは、const
オブジェクトが自身のフィールドを変更できるようにするために使用されます。あなたの例だけでは、mutable
修飾子を削除すると、次の行でコンパイラ エラーが発生します。
rno = 90;
宣言されたオブジェクトはconst
(デフォルトでは) そのインスタンス変数を変更できないためです。
以外の唯一の回避策はofmutable
を実行することですが、これは非常にハックです。const_cast
this
また、 const の場合std::map
、インデックス ing 演算子を使用してアクセスできない sを処理するときにも便利です。[]
あなたの特定のケースでは、嘘をついて欺くために使用されます。
student s(10);
データが欲しいですか?もちろん、電話してgetdata()
ください。
s.getdata();
あなたはデータを取得すると思っていましたが、実際には に変更さs.rno
れました90
。はっ!そして、あなたはそれが安全だと思っていましgetdata
たconst
...