通过 const 限定对象调用成员函数会出错,因为函数未标记为 const?

Calling member function through const qualified object gives error as function is not marked as const?

代码

#include <iostream>
class A
{
public:
    mutable int x;
    mutable int y;

    A(int k1 = 0, int k2 = 0) :x(k1), y(k2) {}

    void display()
    {
        std::cout << x << "," << y << "\n";
    }
};

int main()
{
    const A a1;
    a1.x = 3;
    a1.y = 8;
    a1.display();
    return 0;
}

输出

Error: 'this' argument to member function 'display' 
        has type 'const A', but function is not marked const

我只是通过const限定对象a1调用成员函数A::display()。那么,为什么第 a1.display() 行会出错?

Why line a1.display() is giving an error ?

mutable 变量允许您修改 const 合格函数内的成员变量。

它不允许您调用要通过 const 合格实例调用的 non-const 合格成员函数。因此,你需要一个 const 成员函数。