调用并初始化类的静态成员函数



我有以下代码:

#include <stdint.h>
#include <inttypes.h>
#include <stdio.h>
class A {
public:
int f();
int (A::*x)();
};
int A::f() {
return 1;
}
int main() {
A a;
a.x = &A::f;
printf("%dn",(a.*(a.x))());
}

可以正确初始化函数指针。但是我想让函数指针变成静态的,我想在这个类的所有对象中保持这个的一个副本。当我将它声明为静态

class A {
public:
int f();
static int (A::*x)();
};

我不确定将其初始化为函数f的方式/语法。任何资源都会有所帮助

指向成员函数的静态指针(我想你已经知道这与指向静态成员函数的指针不同)是一种静态成员数据,所以你必须在类之外提供一个定义,就像你对其他静态成员数据所做的那样。

class A
{
public:
int f();
static int (A::*x)();
};
// readable version
using ptr_to_A_memfn = int (A::*)(void);
ptr_to_A_memfn A::x = &A::f;
// single-line version
int (A::* A::x)(void) = &A::f;
int main()
{
A a;
printf("%dn",(a.*(A::x))());
}

最新更新