黑马程序员
4.3.3空指针访问成员函数
可以创建一个指向类person的空指针,可以通过这个空指针来调用该对象中的成员函数,但是不可以访问变量,会报错。这是因为指针并没指向任何内容,因此该对象是不存在的,更不要说对象的成员变量了,更是不存在的。
#include<iostream>
using namespace std;
class Person {
public:
void showClassName() {
cout << "this is Person class" << endl;
}
void showPersonAge() {
if (this == NULL) { return; }
//报错的原因是传入的指针为NULL
cout << "Age = " << this->m_Age << endl;
}
int m_Age;
};
void test01() {
Person * p = NULL;
p->showClassName();//可以运行
p->showPersonAge();//不可以运行,不可访问该成员变量,因为该对象不存在。
}
int main() {
test01();
system("pause");
return 0;
}
4.3.4 const修饰成员函数
#include<iostream>
using namespace std;
//常函数
class Person {
public:
//this 指针的本质 是指针常量 指针的指向是不可以修改的 但指向的值是可以修改的
// const Person * const this;
//在成员函数后面加const,修饰this指针指向,让其指向的值也不可修改
void showPerson() const {
this->m_B = 100;
//this->m_A = 100;//常函数中不允许修改指针指向的值
//this = NULL; //this 指针是不可以修改指针的指向的
}
void func() {
m_A = 100;
}
int m_A;
mutable int m_B;//特殊变量,即使在常函数中,也可以修改这个值,加关键字mutable
};
void test01() {
Person p;
p.showPerson();
}
//常对象
void test02() {
const Person p;//在对象前加const,变为常对象
//p.m_A = 100;//常对象的成员变量属性不可修改
p.m_B = 100; //m_B是特殊值,在常对象下可以修改。
//常对象只能调用常函数
p.showPerson();
//p.func();//常对象不可以调用普通成员函数,因为普通成员函数可以修改成员变量。
}
int main() {
system("pause");
return 0;
}