make 方法不更改自己的类变量而不使它们常量

Making method not change its own class variables without making them constant

本文关键字:常量 自己的 方法 make 类变量      更新时间:2023-10-16

>假设一个类中有变量,并且该类的方法不应在不使变量恒定的情况下更改成员变量。如果可能的话,如何实现?

是的。 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 {
}