c++之空指针访问成员函数

#include<iostream>
using namespace std;
class Person {
public:
    int age;
    void showClass() {
        cout << "这是Person类" << endl;
    }
    void showAge() {
        //解决方法,如果是空就直接返回
        if (this == NULL) {
            return;
        }
        cout << "年龄是:" << this->age << endl;
    }
};
void test() {
    Person* p = NULL;
    //p->showAge();会报错,因为空指针访问成员属性不可行
    p->showClass();
}
int main() {
    test();
    system("pause");
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/xiximayou/p/12096066.html
今日推荐