在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.
}
本文探讨了在C++中如何通过类指针调用成员函数,特别是当指针为空时的情况。尽管空指针调用未使用成员变量的函数不会立即导致错误,但尝试访问成员变量将引发段错误。通过示例代码展示了静态函数和非静态函数的调用差异,强调了正确理解和使用this指针的重要性。
1万+

被折叠的 条评论
为什么被折叠?



