一、空指针访问成员函数
C++中空指针也是可以调用成员函数的,但是也要注意有没有用到this指针
如果用到this指针,需要加以判断保证代码的健壮性
#include<iostream>
using namespace std;
class Person
{
public:
void ShowClassName()
{
cout << "this is Person class" << endl;
}
void ShowClassAge()
{
//报错原因:传入的指针为NULL 添加以下代码:
if (this == NULL)
{
return;
}
//cout << "age = " << m_Age << endl;//属性前面默认加了一个this->,表示是当前对象的一个属性,如下
cout << "age = " <<this->m_Age<< endl;
}
int m_Age;
};
void test()
{
Person *p = NULL;
//p->ShowClassName();//空指针,可以调用成员函数
p->ShowClassAge();//但是如果成员函数中用到了this指针,就不可以了
}
int main()
{
test();
return 0;
}
二、const修饰成员函数
1.常函数:
成员函数后加const后我们称为这个函数为常函数
常函数内不可以修改成员属性
成员属性声明时加关键字mutable后,在常函数中依然可以修改
2.常对象:
声明对象前加const称该对象为常对象
常对象只能调用常函数
#include<iostream>
using namespace std;
//常函数
class Person
{
public:
//this指针的本质是指针常量 指针的指向不可以修改,值可以修改
//const Person * const this; const修饰的是this 在前面加const表示值也不可修改
//在成员函数后面加const,修饰的是this指针,让指针指向的值也不可以修改
void showPerson() const//加入const 值也不能修改了
{
this->m_B = 100;
//this->m_A = 100; //m_A = 100;(本质是前面的,因为隐含一个this指针)不加const则可以修改
//this = NULL;//this指针不可以修改指针的指向,但可以修改值
}
void func()
{
m_A = 100;
}
int m_A;
mutable int m_B;//特殊变量,即使在常函数中,也可以修改这个值,加上关键字mutable
};
void test01()
{
Person p;
p.showPerson();//当用对象p调用showPerson()时,this指向则为p,不可修改
}
//常对象
void test02()
{
const Person p;//在对象前加const,变为常对象
//p.m_A = 100;//不能修改
p.m_B = 100;//m_B是特殊值,在常对象下也可以修改
//常对象只能调用常函数
p.showPerson();
//p.func();//常对象不可以调用普通成员函数,因为普通成员函数可以修改属性
}
int main()
{
return 0;
}