空指针访问成员函数

空指针访问成员函数

  • C++中空指针也是可以调用成员函数的,但是也要注意有没有用到this指针
  • 如果用到this指针,需要加以判断保证代码的健壮性

代码示例:

#include <iostream>
using namespace std;
class Person
{
   
public:
       void showClassName()
       {
   
              cout << "this is Person class" << endl;
       }
       void showPersonAge()
       {
   
              //报错原因是因为传入的指针为NULL
              if (this == NULL)
              {
   
                     return;
              }
              cout << "age=" <<this->m_Age<< endl;
       }
       int m_Age;
       
};
void test01()
{
   
       Person *p = NULL;
       p->showClassName();
       p->showPersonAge();
}
int main()
{
   
       test01();
       return 0;
}

欢迎关注微信公众号:黑马金牌编程

C/C++基础 文章被收录于专栏

本专栏收录C/C++编程语言相关知识

全部评论

相关推荐

昨天 11:42
江西农业大学 C++
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
今天 11:55
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务