如果成员函数没有用到this,那么空指针可以直接访问

如果成员函数用的this指针,就要注意,可以加if判断,如果this为NULL就return, 否则直接报错

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

class People
{
public:
    void Show()                    //相当于void Show(People * this) 
    {
        cout << "People Show" << endl;        //并没有用到this 所以可以访问
    }
    void ShowAge()
    {
        if (this == NULL)            //判断是否是空指针
        {
            return;    
        }
        cout << this->m_Age << endl;  //此时用到了this  相当于 NULL->m_Age
    }

    int m_Age;
};
void Test201()
{
    People * p = NULL;
    p->Show();    //没用到this 可以访问
    p->ShowAge();    //用到this 不加判断直接报错
}

int main()
{
    system("Pause");        //阻塞功能
    return EXIT_SUCCESS;    // 返回正常退出
}

 

相关文章:

  • 2022-12-23
  • 2022-02-13
  • 2022-12-23
  • 2021-09-01
  • 2021-12-29
  • 2022-12-23
  • 2022-12-23
  • 2021-09-20
猜你喜欢
  • 2022-01-10
  • 2021-09-11
  • 2022-12-23
  • 2021-05-02
  • 2021-11-24
  • 2021-06-26
  • 2022-01-02
相关资源
相似解决方案