空指针访问成员函数

mac2024-10-20  10

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

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

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