关于C++的成员函数调用

在C++中,我们都知道类的静态成员函数是可以不用实例化类的对象而直接调用的。但是对类的普通成员函数,我们可以用类的指针来调用,即使这个指针为空。

其实在使用类指针来调用类的成员函数时, 类指针是作为参数"this"指针来传递给函数的。只要该函数没有使用到this指针(包括隐性的使用,比如类的成员变量等),并不会出现segment fault。

闲言少叙,用代码说话吧。

#include <iostream>
using namespace std;
class A
{
public:
    static void static_function(void);
    void function_a(void);
    void function_b(int val);
   
private:
    int element_a;
};

void A::static_function(void)
{
    cout << "This is a static function!" << endl;
}

void  A::function_a(void)
{
    cout << "function_a" << endl;
}

void  A::function_b(int val)
{
    cout << "function_b" << endl;
    element_a = val;
    cout << element_a << endl;
}


int main()
{
    A::static_function();//This is OK, static function.
    
    //A::function_a();  //Compile error
   
    /**************************/
    //This is also OK, although the pointer is not initialized. Because this function never fetch the members of class A
    A * ptr_A = NULL;
    ptr_A->function_a();
    /**************************/
   
   // ptr_A->function_b(5);//This will lead to segment fault, because pointer "this" is null.
}


 

发布了50 篇原创文章 · 获赞 10 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/l_z_s_001/article/details/41113309