常函数:
(1)成员函数后加const后我们称为这个函数为常函数
(2)常函数内不可以修改成员属性
(3)成员属性声明时加关键字mutable后,在常函数中依然可以修改
class Person
{
public:
void test01(int a) const
{
//m_a = a;常函数内不可以修改成员属性
m_b = a; //成员属性声明时加关键字mutable后,在常函数中依然可以修改
}
int m_a;
mutable int m_b;
};
int main()
{
Person p1;
p1.test01(10);
return 0;
}
常对象:
(1)声明对象前加const称该对象为常对象
(2)常对象只能调用常函数
class Person
{
public:
void test01(int a)
{
}
void test02(int a)const
{
}
int m_a;
int m_b;
};
int main()
{
const Person p1;
//p1.m_a = 10;常函数成员变量不可以发生改变
//p1.test01();
p1.test02(10);//常对象只能调用常函数
return 0;
}