【发布时间】:2012-08-20 19:09:30
【问题描述】:
class student {
mutable int rno;
public:
student(int r) {
rno = r;
}
void getdata() const {
rno = 90;
}
};
【问题讨论】:
标签: c++
class student {
mutable int rno;
public:
student(int r) {
rno = r;
}
void getdata() const {
rno = 90;
}
};
【问题讨论】:
标签: c++
它允许您通过 student 成员函数向 rno 成员写入(即“变异”),即使与 student 类型的 const 对象一起使用也是如此。
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
}
};
【讨论】:
const 限定符的成员函数内部。让我编辑我的答案...
使用mutable 关键字以便const 对象可以更改自身的字段。仅在您的示例中,如果您要删除 mutable 限定符,那么您将在
rno = 90;
因为声明为const 的对象不能(默认)修改它的实例变量。
除了mutable 之外,唯一的其他解决方法是对this 进行const_cast,这确实很hacky。
在处理std::maps 时也派上用场,如果它们是 const,则无法使用 indexing 运算符 [] 访问。
【讨论】:
在你的特殊情况下,它被用来撒谎和欺骗。
student s(10);
你想要数据?当然,只需致电getdata()。
s.getdata();
你以为你会得到数据,但我实际上将 s.rno 更改为 90。哈!而你认为这是安全的,getdata 是 const 等等......
【讨论】:
Why is Mutable keyword used,而不是what does mutable mean...