空指針訪問成員函數
C++中空指針也是可以調用成員函數的,但是也要注意有沒有用到this指針
如果用到this指針,需要加以判斷保證代碼的健壯性
class Animal {
public:void fun1() {//正常的成員函數}void fun2() {if (this == NULL) {return;//如果沒有這個return會報錯}//隱含了this的成員函數cout << mAge << endl;//因為用到mAge,其實是this->mAge的簡寫}public:int mAge;
};int main() {Animal * p = NULL;//空指針p->fun1(); //空指針,可以調用成員函數p->fun2(); //但是如果成員函數中用到了this指針,就可能觸發異常
}