#include2.const修饰成员函数成员对象#include using namespace std; class Person { public: void fun() { cout<<"fun()"< //判断指针是否为空,避免空指针导致报错 if (this == NULL) { return; } cout<<"m_age"< Person * p = NULL; //p->fun(); p->fun1(); return 0; }
常函数
- 成员函数后加const即为常函数
- 常函数内不可以修改成员属性
- 成员属性声明时加关键字mutable后,在常函数中依然可以修改
常对象
- 声明对象前加const即为常对象
- 常对象只能调用常函数
#include#include using namespace std; class Person { public: //const 修饰变为常函数 //this指针的本质是指针常量,指针的指向不可以修改 //const Person * const this; //在成员函数后加const ,修饰this指针指向,指针指向不能修改 void fun() const { this->m_age = 90;// error C2166: 左值指定 const 对象 cout<<"fun()"< //Person p; //p.fun(); const Person p1;//常对象 p1.m_ID = 90;// error C3892: “p1”: 不能给常量赋值 return 0; }



