常函数:
- 成员函数后加const,我们称这个函数为常函数
- 常函数内不可以修改成员属性
- 成员属性声明时加关键字mutable后,在常函数中依然可以修改
常对象:
- 声明对象前加const,称为常对象
- 常对象只能调用常函数
//常函数
class Person
{
public:
//this指针的本质 是指针常量 指针的指向不可以修改
//const Person * const this;
//在成员函数后加const,修饰的是this指针,让this指向的值也不能修改
Person showPerson() const
{
//m_A = 100;//报错
this->m_B = 100;
}
void func()
{
}
int m_A;
mutable int m_B;//特殊变量,即使在常函数中,也可以修改这个值
};
void test01()
{
Person p;
p.showPerson();
}
//常对象
void test02()
{
const Person p;//在对象前加const,变为常对象
// p.m_A = 100;报错
p.m_B = 100;//特殊值,在常对象下也可以修改
//常对象只能调用常函数
//p.func()报错
}