C++ constant function

Constant function

1. After adding const after the member function, we call this function a constant function.
2. It is not possible to modify member attributes in regular functions.
3. After adding the keyword mutable in the member attribute declaration, it can still be modified in the regular function.
4. Adding const before the declared object to call the object a regular object.
5. Constant objects can only call constant functions. The
code is as follows:

class Person
{
    
    
public:
	void showPerson() const
	{
    
    
		//this->m_A = 100;
		this->m_B = 100;
		//this = NULL;
	}

	void func(){
    
    }

	int m_A=100;
	mutable int m_B;//加mutable,特殊变量,在常函数中,也是可以修改这个值的
};

The test code is as follows:

    const Person p;
	//p.m_A=100; 会报错,m_A在常函数内,不可以修改
	p.m_B = 100;//不会报错
	p.showPerson();//不会报错,常对象只能调用常函数
	//p.func();  会报错,常对象不可调用“非”常函数 
	cout << "p中的属性m_A为:" << p.m_A << endl;

Test Results:

p中的属性m_A为:100
请按任意键继续. . .

Guess you like

Origin blog.csdn.net/Little_XWB/article/details/108185377