#include <iostream>
using namespace std;
//1 解决名称冲突
class Person {
public:
void print() {
cout << "print" << endl;
}
void printAge() {
if (this == NULL) {//没有这一判断,直接运行,目前跟学习视频里面的报错不一样,这里是不报错的,但是debug运行就有错误了
return;
}
// cout << "age" << this->age << endl;//age其实就是this->age
cout << "age" << this->age << endl;
}
int age;
};
void test() {
Person *p = NULL;
p->print();
p->printAge();
}
int main() {
test();
return 0;
}
C++空指针访问成员函数
最新推荐文章于 2025-02-25 01:44:38 发布
本文通过一个C++程序示例介绍了如何在使用空指针时避免程序崩溃,特别是展示了在调用成员函数前检查指针是否为空的重要性。代码中定义了一个Person类,并在成员函数中加入了空指针检查逻辑。
123

被折叠的 条评论
为什么被折叠?



