360笔试题 类指针,该如何解决

360笔试题 类指针

#include <iostream>
using namespace std;

class A{
public:
void a(){
cout << "func_a" << endl;
}
};

int main(){
A * p = NULL;
p -> a();
return 0;
}



为何输出func_a,背后的原理是什么?

------解决方案--------------------
给你看个例子:

class Obj {
public:
  void func() { return a; }
private:
  int a;
};

p->func()等价于:
void func(Obj *this) {
  return this->a;
}
func(p); //当然你在C++里面不能这么写

现在你这个例子里面
p = NULL;
那么传递进去的this指针就是NULL,相当于func(NULL)。但是你没有引用类里面的任何变量,所以程序运行通过.