• 空指针访问成员函数


    如果成员函数没有用到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;    // 返回正常退出
    }
  • 相关阅读:
    JavaScript学习笔记之数组(一)
    Ajax与CORS通信
    JSONP跨域
    JavaScript原型与原型链
    CSS布局套路
    爱奇艺的自制节目
    2019.3.6错误经验
    Kickdown UVA
    ASP.NET Web
    C# Windows
  • 原文地址:https://www.cnblogs.com/yifengs/p/15170139.html
Copyright © 2020-2023  润新知