>假设一个类中有变量,并且该类的方法不应在不使变量恒定的情况下更改成员变量。如果可能的话,如何实现?
是的。 const
-限定成员函数:
struct X {
int a;
void f() const {
// a = 42; // illegal
}
};
使用常量方法。例如:
class Foo {
public:
// this won't be able to change any member variable
void bar() const;
}
void Foo::bar() const {
}