C++关于const修饰成员函数

大家好,我是一个C++初学者,最近在学const修饰成员函数

下面这行代码,报了一个错误,this指针不能指向一个常量,我想请教一下是为什么?


#include 
using namespace std;
class Person
{
public:
    void showperson()
    {
        this->m_a=100;
    }
    int m_a;
};
void test02()
{
    const Person p;
    p.showperson();
    //p.m_a=100;

}
int main()
{
    test02();
    system("pause");
    return 0;
}

因为对象p被const修饰, 表示该对象无法被修改, 但是p.showperson()并没有const后缀修饰, 导致编译器认为该函数可能会有修改对象的可能. 因此编译器报此错误.

img


如有帮助,欢迎点赞采纳哈~