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

标签 c++ class function-pointers pointer-to-member

我有以下代码:

#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/

相关文章:

c++ - c++17 中的动态异常规范是否无效?

c++ - 重载 *= 用于复数

c - 结构体函数指针错误

c - 初始化一个结构数组,其中包含函数指针 C

c++ - C++ 模拟创建两个重叠的 win32 窗口

c++ - 如何使用指针从不同的函数访问局部变量?

c++ - 当方法只接受一个参数时,如何比较两个对象?

java - 协助构建具有多个类别的体育游戏

c - 如何将N字节参数传递给指针调用的函数

c++ - 模板依赖实现