This question already has answers here:
Why can a const member function modify a static data member?

(4个答案)


3年前关闭。




我有C++中Eckel-Thining的以下代码行
Class Obj{
    static int i,j;
    public:
    void f() const {cout<<i++<<endl;}
    void f() const {cout<<i++<<endl;}
};
int Obj::i=47;
int Obj::j=11;

现在,它是用Ecekl编写的用于const成员函数的,通过声明成员函数const,我们告诉编译器不要修改类数据。我了解到在某些特定情况下,例如可变const并通过显式放弃此指针的constness,我们可以消除它,但是在此两者均未发生且i ++和j ++可以正常工作。为什么会这样呢?

最佳答案

const仅适用于对象(this指针为const),允许修改static members

关于c++ - 为什么此const成员函数会修改静态成员数据? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15332037/

10-11 22:37
查看更多