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

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

    1. //空指针调用成员函数
    2. class Person
    3. {
    4. public:
    5. void showClassName()
    6. {
    7. cout << "this is Person class" << endl;
    8. }
    9. void showPersonAge()
    10. {
    11. //报错原因是因为传入的指针是为NULL
    12. if (this == NULL)
    13. {
    14. return;
    15. }
    16. cout << "age = " << this->m_Age << endl;
    17. }
    18. int m_Age;
    19. };
    20. void test01()
    21. {
    22. Person* p = NULL;
    23. p->showClassName();
    24. p->showPersonAge(); //报错 空指针不能访问成员属性
    25. }
    26. int main()
    27. {
    28. test01();
    29. system("pause");
    30. return 0;
    31. }