const修饰this指针
class Person{public://this 指针的本质是 Person * const this//是一个指针常量,这个指针常量指向对象,且不可更改//因此除非对象是空,否则this不为空,且不可作为左值修改//在成员函数后面加const 修饰的是this的指向,//让指针指向的值也不可修改//加const后本质是 const Person * const thisvoid showPerson() //const// 加在这里{this->m_a = 0;//this = NULL;}int m_a;};
若想修改在常函数中的变量,需要在变量前加入mutable修饰符
mutable修饰符
#include <iostream>#include <string>using namespace std;class Person{public:void showPerson() //const// 加在这里{//this->m_a = 0;//this = NULL;}void fun() const{this->m_b = 10;}int m_a;mutable int m_b; //mutable修饰符可令其在常函数中也可被修改};
常函数:
- 成员函数后加const后我们称为这个函数为常函数
 - 常函数内不可以修改成员属性
 - 成员属性声明时加关键字mutable后,在常函数中依然可以修改
 
常对象:
- 声明对象前加const称该对象为常对象
 - 常对象只能调用常函数
 
示例:
class Person {public:Person() {m_A = 0;m_B = 0;}//this指针的本质是一个指针常量,指针的指向不可修改//如果想让指针指向的值也不可以修改,需要声明常函数void ShowPerson() const {//const Type* const pointer;//this = NULL; //不能修改指针的指向 Person* const this;//this->mA = 100; //但是this指针指向的对象的数据是可以修改的//const修饰成员函数,表示指针指向的内存空间的数据不能修改,除了mutable修饰的变量this->m_B = 100;}void MyFunc() const {//mA = 10000;}public:int m_A;mutable int m_B; //可修改 可变的};//const修饰对象 常对象void test01() {const Person person; //常量对象cout << person.m_A << endl;//person.mA = 100; //常对象不能修改成员变量的值,但是可以访问person.m_B = 100; //但是常对象可以修改mutable修饰成员变量//常对象访问成员函数person.MyFunc(); //常对象不能调用const的函数}int main() {test01();system("pause");return 0;}
