1.空指针访问成员函数
注释中有预防空指针的办法。在要调用类中属性的那个函数里加
if(this == NULL)
{
return;
}
在程序因为空指针崩溃前就结束掉程序
class person
{
public:
void classname()
{
cout << "person class" << endl;
}
void personage()
{
//解决方法
if (this == NULL)
{
return; //如果this指向空指针,跳出这个函数,不执行下一句了
}
cout << "person age = " << m_age << endl;
}
int m_age;
};
void test()
{
person *p = NULL; //这里p为指针变量,为空指针。注意:指针指向要用->
p->classname(); //对象没实体,但没用到对象,所以可以运行
p->personage(); //这个不能实现,因为属性前默认this->m_age,而此时this指向的person的对象是一个空指针
//对象没有实体,所以属性自然也不能输出。有解决办法
}
int main()
{
test();
system("pause");
return 0;
}
2. const修饰成员函数
常函数:
- 成员函数后加const,称这个函数为常函数(void func() const)
- 常函数内不可修改成员属性
- 成员属性声明时加关键字mutable后,在常函数中依然可以修改
常对象:
- 声明对象前加const,称之为常对象
- 常对象只能调用常函数
//不加const时为person * const this 指针指向不可修改
//加了const后为const person * const this ,指针指向的值和指向都不能修改
class person
{
public:
//this指针的本质是一个指针常量,指针的指向是不可以修改的。没加const时,值可以修改
//不加const时为person * const this 指针指向不可修改
//加了const后为const person * const this ,指针指向的值和指向都不能修改
void personage() const //常函数
{
m_tel = 103; //定义时加了mutable就可以修改了
//this->m_age = 100;//每个成员函数内都有一个this指针
//this = NULL;报错,因为指针已指向p,不可以修改指向了
}
int m_age;
mutable int m_tel;
};
void func() //一般函数
{
}
void test()
{
const person p; //常对象
//p.m_age = 100;不可修改
p.m_tel = 100; //可修改
p.personage();
//p.func(); //常对象只能调用常函数
}
int main()
{
test();
system("pause");
return 0;
}