如果一個類的指針指向空,它仍然可以調用某些成員函數,這些成員函數要求在函數內部沒有用到this指針,對於要用到this指針的函數,這個指針去調用會訪問越界.
所以在下面的代碼裏,指針的前兩處調用是打印出了結果,但在第三句處程序崩潰.
#include<iostream>
using namespace std;class A
{
public:
A()
{
m = 99;
}
static void test1()
{
cout<<"test1"<<endl;
}
void test2()
{
cout<<"test2"<<endl;
}
void test3()
{
cout<<"test3"<<endl;
}
void test4()
{
cout<<m<<endl;
}
int m;
};
int main()
{
A *ptr =NULL;
ptr->test1();
ptr->test2();
ptr->test4();
return 0;
}
結果:
test1
test2
段錯誤(核心已轉儲)