可能重复:
C++“可变”关键字
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;
}
};
即使与type 的对象一起使用,它也允许您rno通过成员函数向成员写入(即“变异”)。studentconststudent
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不能(默认)修改它的实例变量。
除了mutable, 唯一的其他解决方法是做 a const_castof this,这确实很hacky。
它在处理 s 时也派上用场,如果它们是 const std::map,则无法使用 indexing 运算符访问。[]
在您的特定情况下,它被用来撒谎和欺骗。
student s(10);
你要数据?当然,只要打电话getdata()。
s.getdata();
你以为你会得到数据,但我实际上s.rno改为90. 哈!你认为它是安全的,getdata存在const和所有...