首页 > 解决方案 > 调用和初始化类的静态成员函数

问题描述

我有以下代码:

#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 的方式/语法。任何资源都会有所帮助

标签: c++classfunction-pointersmember-function-pointers

解决方案


A static pointer-to-member-function (I guess you already know this is different from a pointer to a static member function) is a kind of static member data, so you have to provide a definition outside the class like you would do with other static member data.

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))());
}

推荐阅读