我有以下代码:
#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("%d\n",(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("%d\n",(a.*(A::x))());
}
关于c++ - 调用并初始化类的静态成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65945941/