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