Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

C++里为什么空指针也能调用函数成员?

#include <iostream>
using namespace std;

class A{
public:
    void f(){ cout<<this<<endl; }
};

int main()
{
    A *a = nullptr;
    a->f();
    
    return 0;
} 

程序输出:

0

为什么 a->f() 这种空指针调用成员函数是允许的?它的机制是什么?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

类实例 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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...