Class and object-const modified member function

Class and object-const modified member function

Constant function:
·After adding const after a member function, we call this function a constant function . The
member attributes cannot be modified in a constant function
. After adding the keyword mutable when the member properties are clear, the
constant object can still be modified in the constant function :
·Add const before the object declaration to call the object a constant object
·The constant object can only call the constant function

#include<iostream>
using namespace std;
//常函数
class person
{
    
    
public:
	//this指针的本质是指针常量 指针的指向是不可以修改的
	//const Person *const this;
	//在成员函数后面加const,修饰的是this指针,让指针指向的值也不可以修改
	void showperson() const//常函数
	{
    
    
		this->m_B = 233;
		//this->m_A = 233;
		//this = NULL; //this指针不可以修改指针的指向的

	}
	void func()
	{
    
    
		m_A = 137;
	}
	int m_A;
	mutable int m_B;//特殊变量,即使在常函数中,也可以修改这个值,加关键字mutable
};
void test01()
{
    
    
	person p;
	p.showperson();
}
//常对象
void test02()
{
    
    
	const person p; //在对象前加const,变为常对象
	//p.m_A = 233;
	p.m_B = 233;//m_B是特殊值,在常对象下也可以修改
	//常对象只能调用常函数
	p.showperson();
	//p.func;//常对象不可以调用普通成员函数,因为普通成员函数可以修改属性
}
int main()
{
    
    
	system("pause");
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_54673833/article/details/114011558