C++ 在不使用单独的 typedef 的情况下声明函数指针数组的语法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5093090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:21:20  来源:igfitidea点击:

What's the syntax for declaring an array of function pointers without using a separate typedef?

c++arrayssyntaxfunction-pointerstypedef

提问by Maxpm

Arrays of function pointers can be created like so:

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

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

What is the syntax for creating a function pointer array without using the typedef?

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

回答by Armen Tsirunyan

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 

so your answer is

所以你的答案是

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

But naturally, this is a bad practice, just use typedefs:)

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

Extra:Wonder how to declare an array of 3 pointers to functions taking int and returning a pointer to an array of 4 pointers to functions taking double and returning char? (how cool is that, huh? :))

额外:想知道如何声明一个包含 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

:))

:))

回答by Logan Capaldo

Remember "delcaration mimics use". So to use said array you'd say

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

 (*FunctionPointers[0])();

Correct? Therefore to declare it, you use the same:

正确的?因此要声明它,您使用相同的:

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

回答by Erik

Use this:

用这个:

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

Works like everything else, you place [] after the name.

像其他一切一样工作,您将 [] 放在名称后面。