C++静态函数指针数组的初始化

C++ Initialization of static function pointer array

我想创建一个静态函数指针数组,这样我就可以根据接收到的索引跳转到某个函数。就像索引跳线一样。

想象一下这样的 class:

Class A 
{ 
  private:
  static void 1stFunction();
  static void 2ndFunction();

  static void(*functionPointer[20])(void);

};

然后我希望 functionPointer 获得 1stFunction 和 2ndFunction 的值,甚至更多。 那么,我该如何初始化它呢? 据我所知,在声明静态成员时,您甚至可以在创建实例之前使用它。所以我虽然,让我们初始化那个函数指针,所以以后我可以这样调用它

functionPointer[receivedIndex]();

所以我尝试在同一个 .h 文件中像这样初始化它

void (*A::functionPointer[])(void) =
{
    A::1stFunction,
    A::2ndFunction,
};

但是编译器给了我重新定义,它说它已经创建了。

所以,很确定我遗漏了什么。但我不知道,如果它是语法或者根本不可能这样做。 我知道指向 class 的成员函数的函数指针与普通函数指针不同......但这是一个静态函数,所以我相信它不属于一个实例,因此它应该与普通函数一起工作指针。

如有任何帮助,我们将不胜感激。 谢谢

下面是一个可能满足您需要的工作示例。

您需要 C++11 作为初始值设定项列表。

最好在 cpp 文件中初始化静态成员,因为您不希望每次包含 header 时都定义静态成员(这可以导致链接问题)。

您可以根据函数指针数组的初始化,用所需的index调用callf并调用相应的函数。

程序的输出为:

I am 2ndFunction

Header 文件

class A
{
private:
  static void Function1();
  static void Function2();

  static void(*functionPointer[20])();

public:
  static void callf(int index);
};

实施

#include <iostream>
#include "ex.h"

void(*A::functionPointer[20])() {
  A::Function1,
  A::Function2
};

void A::Function1() {
  std::cout << "I am 1stFunction" << std::endl;
}

void A::Function2() {
  std::cout << "I am 2ndFunction" << std::endl;
}

void A::callf(int index) {
  A::functionPointer[index]();
}

int main(int argc, char const *argv[]) {
  A::callf(1);
  return 0;
}

这里有更现代的 C++ 方法(需要 C++14) 如果您不局限于 C++03,我建议您探索 lambda 函数。

#include <iostream>
#include <functional>
#include <vector>

class A {
public:

  using f_type = std::function<void(void)>;
  f_type f1 = []() { std::cout << "f0" << std::endl;};
  f_type f2 = []() { std::cout << "f1" << std::endl;};
  static void f3() { std::cout << "f3" << std::endl; }

  std::vector<f_type> functions{f1, f2, f3};

};


int main() {

  A a;
  a.functions[0]();
  a.functions[1]();
  //adding custom lambda
  a.functions.emplace_back([](){ std::cout << "custom f" << std::endl;});
  a.functions[2]();

  return 0;
}

您可以将函数和 lambda 添加到您的容器中。