首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >c++之空指针访问成员函数

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

作者头像
西西嘛呦
发布于 2020-08-26 15:56:16
发布于 2020-08-26 15:56:16
1.1K0
举报
代码语言:javascript
复制
#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;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-12-25 ,如有侵权请联系 cloudcommunity@tencent.com 删除
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档