What is the matter of adding const after member function in C++?

This is actually a regular function, and the member attributes cannot be modified in the regular function, but after adding mutable to the member attribute, it can still be modified in the regular function.
For example: the following code is correct.

// An highlighted block
class Person {
    
    
	
public:
	void showPerson() const {
    
    
		this->m_A = 100;
	}
	mutable int m_A;
};

However, if you remove mutable, the result is wrong and an error will be reported.

When it comes to constant functions, you have to mention constant objects. Add const before the object to declare the object as a constant object. The constant object can only call the constant function , for example:

In the following functions, no error will be reported in the test function, but an error will be reported in the main function, showing (error (active) E1086 object contains a type qualifier that is incompatible with the member function "Person::fun"), namely: The constant object can only call a constant function, showPerson is a constant function, and fun is a normal function .

// An highlighted block
#include<iostream>
using namespace std;
class Person {
    
    
	
public:
	void showPerson() const {
    
    
		this->m_A = 100;
	}
	void fun() {
    
    

	}
	mutable int m_A;
};
void test() {
    
    
	const Person p;
	p.m_A = 100;
	p.showPerson();
}
int main() {
    
    
	const Person p;
	p.fun();
}

Everyone's praise is the greatest support for me.

Guess you like

Origin blog.csdn.net/myf_666/article/details/113588929