繁体   English   中英

你能解释下面的C / C ++语句吗?

[英]Can you explain the following C/C++ statement?

void (*func)(int(*[ ])());

读取毛茸茸的声明符的一般过程是找到最左边的标识符并解决问题,在*之前记住[]()绑定(即, *a[]是指针数组,而不是指向数组的指针)。 由于缺少参数列表中的标识符,这种情况变得更加困难,但是[]再次绑定* ,因此我们知道*[]表示一个poitners数组。

所以,给定

void (*func)(int(*[ ])());

我们按如下方式细分:

       func                   -- func
      *func                   -- is a pointer
     (*func)(           )     -- to a function taking
     (*func)(     [ ]   )     --    an array
     (*func)(    *[ ]   )     --    of pointers
     (*func)(   (*[ ])())     --    to functions taking 
                              --      an unspecified number of parameters
     (*func)(int(*[ ])())     --    returning int
void (*func)(int(*[ ])());    -- and returning void

这在实践中会是什么样子,如下所示:

/**
 * Define the functions that will be part of the function array
 */
int foo() { int i; ...; return i; }
int bar() { int j; ...; return j; }
int baz() { int k; ...; return k; }
/**
 * Define a function that takes the array of pointers to functions
 */
void blurga(int (*fa[])())
{
  int i;
  int x;
  for (i = 0; fa[i] != NULL; i++)
  {
    x = fa[i](); /* or x = (*fa[i])(); */
    ...
  }
}    
...
/**
 * Declare and initialize an array of pointers to functions returning int
 */
int (*funcArray[])() = {foo, bar, baz, NULL};
/**
 * Declare our function pointer
 */
void (*func)(int(*[ ])());
/**
 * Assign the function pointer
 */
func = blurga;
/**
 * Call the function "blurga" through the function pointer "func"
 */
func(funcArray); /* or (*func)(funcArray); */

这不是声明,而是声明。

它将func声明为一个指向func的指针,该函数返回void并获取类型为int (*[])()的单个参数,该参数本身是一个指向函数的指针,该函数返回int并获取固定但未指定数量的参数。


cdecl输出你的小信仰:

cdecl> explain void (*f)(int(*[ ])());
declare f as pointer to function (array of pointer to function returning int) returning void

是:

$ cdecl
explain void (* x)(int (*[])());
declare x as pointer to function 
  (array of pointer to function returning int) returning void

void (*func)(blah); 是指向将blah作为参数的函数的指针,其中blah本身是int(*[ ])()是函数指针的数组。

Geordi是一个C ++机器人,允许训练这个:

<litb> geordi: {} void (*func)(int(*[ ])());
<litb> geordi: -r << ETYPE_DESC(func)
<geordi> lvalue pointer to a function taking a pointer to a pointer to a nullary function 
         returning an integer and returning nothing

它可以做很多有用的事情,比如显示所有参数声明(事实上,这只是匹配原始C++语法规则名称):

<litb> geordi: show parameter-declarations
<geordi> `int(*[ ])()`.

让我们朝相反的方向做:

<litb> geordi: {} int func;
<litb> geordi: make func a pointer to function returning void and taking array of pointer to 
       functions returning int
<litb> geordi: show
<geordi> {} void (* func)(int(*[])());

如果你问它,它会执行你给它的任何东西。 如果你受过训练但只是忘记了一些可怕的括号规则,你也可以混合使用C ++和geordi风格的类型描述:

<litb> geordi: make func a (function returning void and taking (int(*)()) []) *
<geordi> {} void (* func)(int(*[])());

玩得开心!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM