c++ 基础知识-类和对象-对象特性
1.空指针访问成员函数
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
void fun()
{
cout<<"fun()"<<endl;
}
void fun1()
{
//判断指针是否为空,避免空指针导致报错
if (this == NULL)
{
return;
}
cout<<"m_age"<<m_age<<endl;//传入空指针,不输出,报错
cout<<"fun1()"<<endl;
}
int m_age;
};
int main()
{
Person * p = NULL;
//p->fun();
p->fun1();
return 0;
}
2.const修饰成员函数成员对象
常函数
- 成员函数后加const即为常函数
- 常函数内不可以修改成员属性
- 成员属性声明时加关键字mutable后,在常函数中依然可以修改
常对象
- 声明对象前加const即为常对象
- 常对象只能调用常函数
#include <iostream>
#include <string>
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()"<<endl;
}
//利用mutable关键字修饰,可以修改
int mutable m_ID;
int mutable m_age;
};
int main()
{
//Person p;
//p.fun();
const Person p1;//常对象
p1.m_ID = 90;// error C3892: “p1”: 不能给常量赋值
return 0;
}