3、空指针访问成员函数.cpp 653 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. //4.3.3 空指针访问成员函数
  2. //C++中空指针也是可以调用成员函数的,但是也要注意有没有用到this指针
  3. //如果用到this指针,需要加以判断保证代码的健壮性
  4. #if(0)
  5. #include <iostream>
  6. class Person
  7. {
  8. public:
  9. void showClassName()
  10. {
  11. std::cout << "This is Person class" << std::endl;
  12. }
  13. void showPersonAge()
  14. {
  15. //报错的原因是因为传入的指针是NULL
  16. if (this == NULL)
  17. {
  18. return;
  19. }
  20. std::cout << "age = " << this->m_Age << std::endl;
  21. }
  22. int m_Age;
  23. };
  24. void test01()
  25. {
  26. Person* p = NULL;
  27. //p->showClassName();
  28. p->showPersonAge();
  29. }
  30. int main()
  31. {
  32. test01();
  33. system("pause");
  34. return 0;
  35. }
  36. #endif