11.3.3重学C++之【空指针访问成员函数】

#include<stdlib.h>
#include<iostream>
#include<string>
using namespace std;


/*
    4.3.3 空指针访问成员函数
        C++中空指针是可以调用成员函数的
        但是注意有没有用到this指针(有坑)
        若用到了this指针,需加以判断来保证代码的健壮性
*/


class Person{
public:

    void show_class_name(){
        cout << "this is person class" << endl;
    }

    void show_age(){
        if(this == NULL){
            return;
        }
        cout << "age=" << this->age << endl;
        // 报错,传入的p是空指针,此时this为空指针;解决办法如上判断
    }

    int age;
};


void test1(){
    Person * p = NULL;
    p->show_class_name();
    p->show_age();
}


int main(){
    test1();

    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/HAIFEI666/article/details/114875075