【问题标题】:What's the syntax for declaring an array of function pointers without using a separate typedef?在不使用单独的 typedef 的情况下声明函数指针数组的语法是什么?
【发布时间】:2011-07-02 20:39:27
【问题描述】:

函数指针数组可以这样创建:

typedef void(*FunctionPointer)();
FunctionPointer functionPointers[] = {/* Stuff here */};

不使用typedef创建函数指针数组的语法是什么?

【问题讨论】:

  • 有趣的问题,但在“真实”代码中,您应该遵循函数指针的黄金法则:使用typedef,否则没有人能够理解您的代码。 :)

标签: c++ arrays syntax function-pointers typedef


【解决方案1】:
arr    //arr 
arr [] //is an array (so index it)
* arr [] //of pointers (so dereference them)
(* arr [])() //to functions taking nothing (so call them with ())
void (* arr [])() //returning void 

所以你的答案是

void (* arr [])() = {};

当然,这是一个不好的做法,只需使用typedefs :)

额外: 想知道如何声明一个包含 3 个指针的数组,该数组指向采用 int 的函数并返回一个指向包含 4 个指针的数组的指针,该指针指向采用 double 并返回 char 的函数? (这有多酷,嗯?:))

arr //arr
arr [3] //is an array of 3 (index it)
* arr [3] //pointers
(* arr [3])(int) //to functions taking int (call it) and
*(* arr [3])(int) //returning a pointer (dereference it)
(*(* arr [3])(int))[4] //to an array of 4
*(*(* arr [3])(int))[4] //pointers
(*(*(* arr [3])(int))[4])(double) //to functions taking double and
char  (*(*(* arr [3])(int))[4])(double) //returning char

:))

【讨论】:

  • 谢谢你,Matteo; cdecl.org 是一个很棒的网站!
  • 该方法的精彩解释! :)
【解决方案2】:

记住“贬义模仿使用”。所以要使用所说的数组,你会说

 (*FunctionPointers[0])();

对吗?因此要声明它,您使用相同的:

 void (*FunctionPointers[])() = { ... };

【讨论】:

    【解决方案3】:

    使用这个:

    void (*FunctionPointers[])() = { };
    

    像其他东西一样工作,你在名字后面加上 []。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-27
      • 1970-01-01
      • 1970-01-01
      • 2014-09-10
      • 1970-01-01
      • 1970-01-01
      • 2021-05-10
      相关资源
      最近更新 更多