BZ易风

导航

 

如果成员函数没有用到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;    // 返回正常退出
}

 

posted on 2021-08-21 17:38  BZ易风  阅读(64)  评论(0编辑  收藏  举报