Mistakes C ++ class of this pointer is null

Code:

 1 class test{
 2     public:
 3     static void f1(){cout<<y<<endl;}
 4     void f2(){cout<<y<<endl;}
 5     void f3(){cout<<x<<endl;}
 6     void f4(int p){cout<<p<<endl;}
 7     int x;
 8     static int y;
 9 };
10 int test::y=1;
11 int main()
12 {
13     test* p=nullptr;
14     p->f1();
15     p->f2();
16     p->f3();
17     p->f4(5);
18     getchar();
19     return 0;
20 }

2. Results:

f1, f2, f4 will call succeeds, f3 call failed.

Explanation:

p is null, this pointer therefore this class is null. When you call a non-static member functions, the compiler will default to this pointer as the first parameter!

f1 itself is a static member function, call the static member variables y, you do not need this pointer, success.

f2 is an ordinary member function, you can also call the static member variables y, do not need this pointer, success.

f3 called ordinary members of variables, then you need this pointer, but this is null, it is equivalent to calling cout << null-> x << endl; this is clearly wrong!

f4 do not need this pointer, success.


Two other related knowledge:

1, static member functions can only call a static member variables, ordinary member function can be called a static member variables.

2. To declare static member variables in the class, outside class initialization.

 

Guess you like

Origin www.cnblogs.com/FdWzy/p/12364934.html