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

Abh*_*ane 0 c++ class constants mutable member-functions

代码

#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;
}
Run Code Online (Sandbox Code Playgroud)

输出

Error: 'this' argument to member function 'display' 
        has type 'const A', but function is not marked const
Run Code Online (Sandbox Code Playgroud)

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

JeJ*_*eJo 5

为什么线路a1.display()会出错?

mutable变量允许您修改限定函数内的成员变量const

它不允许您能够调用non-const通过限定实例调用的限定成员函数const。因此,您需要一个const成员函数。