#include <string>
#include "iostream"
using namespace std;classPerson{public:voidshowClassName(){
cout <<"this is class person"<< endl;}voidshowPersonAge(){if(this== NULL){return;}//报错的原因是传入的指针为NULL
cout <<"age = "<<this-> m_Age <<endl;}int m_Age;};voidtest01(){
Person *p = NULL;
p ->showClassName();
p ->showPersonAge();//不加判断直接运行则会报错}intmain(){test01();
system ("pause");return0;}
四、const修饰成员函数
常函数:
· 成员函数后加 const , 我们称这个函数为常函数。
· 常函数内不可修改成员属性
· 成员属性声明时加关键字 mutable 后, 在常函数中依旧可以修改
常对象:
· 声明对象前加 const
· 常对象只能调用常函数
#include <string>
#include "iostream"
using namespace std;classPerson{public:// this 指针的本质是 指针常量 指针的指向是不可修改的// 相当于 Person *const this// 在成员函数后面加const, 修饰的是this指向, 让指针指向的值也不可以修改// const Person *const thisvoidshowPerson()const{this-> m_B =100;//this -> m_A = 100;//this = NULL //this 指针不可以修改指针的指向}int m_A;
mutable int m_B;//特殊变量, 使得该值在常函数中也可以修改voidfunc(){
m_A =100;//在这里面修改不会报错//但调用时会报错}};voidtest01(){
Person p;
p.showPerson();}voidtest02(){const Person p;
p.m_A =100;
p.m_B =100;//A不可修改
p.showPerson();//常对象只能调用常函数
p.func();//常对象不能调用普通函数,因为普通函数中可以修改常对象的值}intmain(){test01();
system ("pause");return0;}