类实例 a
当然可以调用它的公开成员函数 a->f()
,这是类函数的调用方式,跟 a
是不是空指针无关。
nullptr -> f()
会不会崩溃,取决于 f()
是否依赖类实例相关属性,举例
#include <iostream>
using namespace std;
class A
{
public:
void f1() { cout << "A::f1(): " << this << endl; }
virtual void f2() { cout << "A::f2(): " << this << endl; }
void f3() { cout << "A::f3(): " << this->n << endl; }
static void f4() { cout << "A::f4(): " << endl; }
private:
int n;
};
int main()
{
A* a = nullptr;
a->f1(); // OK
// a->f2(); // FAIL
// a->f3(); // FAIL
a->f4(); // OK
return 0;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…