空指针访问成员函数
发布日期:2021-11-20 10:17:47 浏览次数:9 分类:技术文章

本文共 488 字,大约阅读时间需要 1 分钟。

/*

C++中的空指针也可以调用成员函数,但是也要注意有没有用到this指针

如果用到this指针,需要加以判断保证代码的健壮性

*/

#include "pch.h"#include 
using namespace std;class person {
public: void showclassname() {
cout << "person的名称" << endl; } void showpersonage() {
//..报错原因是因为传入的指针是为NULL //加入: if (this == NULL) {
return; } cout << "年龄" <
m_age << endl; } int m_age;};void test01() {
person* p =NULL; p->showclassname();//这个没报错, p->showpersonage();//这个报错,报错原因是因为传入的指针视为NULL。}int main(){
}

转载地址:https://blog.csdn.net/weixin_43223362/article/details/102846180 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:const修饰成员函数
下一篇:面试重点-this指针

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年04月08日 13时32分20秒