C++:空指针访问类方法

C++:空指针访问类方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
using std::cout;
using std::endl;

class NullPointerCall
{
public:
void func1()
{ cout << "func1()" << endl; }

void func2(int ix)
{ cout << "ix = " << ix << endl; }

void func3(/* NullPointerCall* const this */)
{ cout << "_ix = " << this->_ix << endl; }

private:
int _ix;
};


int main(void)
{
NullPointerCall * p = nullptr;
p->func1();//NullPointerCall::func1(p);
p->func2(10);// NullPointerCall::func2(p, 10);
//p->func3();//error p->func3(p);

NullPointerCall np;
np.func1();//NullPointerCall::func1(&np);
np.func2(10);
np.func3();//np.func3(&np);
return 0;
}