#include <iostream>
using namespace std;
//const修饰成员函数
//成员函数后面加const,称为常函数
//常函数内不可以修改成员属性
//成员属性声明时加mutable,在常函数中依然可以修改
//声明对象前加const,称为常对象
//常对象只能调用常函数
class person{
public:
int m_a;
mutable int m_b;//加上mutable,在常函数中也能修改
//this指针的本质:指针常量,指针的指向不可以修改
//person * const this;
//成员函数后加const,修饰的是this的指向,指针的指向不可以修改
void showPerson()const
{
this->m_b=100;
cout<<m_b;
}
};
void test01(){
person p;
p.showPerson();
cout<<p.m_b;
}
void test02(){
const person p;//常对象
//p.m_a=100;//不可以修改
p.m_b=1000;//在常对象下可以修改
p.showPerson();//常对象只能调用常函数
}
int main ()
{
test02();
return 0;
}
const修饰成员函数
最新推荐文章于 2024-05-20 22:11:41 发布