这是一个语法问题。我强调,我希望理解如何阅读下面的代码。
我很难理解以下代码(1)如何转换为它(2)下的代码:
代码为零:
int addInt(int n, int m) {
return n+m;
}代码一:
// this is a function called functionFactory which receives parameter n
// and returns a pointer to another function which receives two ints
// and it returns another int
int (*functionFactory(int n))(int, int) {
printf("Got parameter %d", n);
int (*functionPtr)(int,int) = &addInt;
return functionPtr;
}代码二:
typedef int (*myFuncDef)(int, int);
// note that the typedef name is indeed myFuncDef
myFuncDef functionFactory(int n) {
printf("Got parameter %d", n);
myFuncDef functionPtr = &addInt;
return functionPtr;
}我正为两件事而挣扎,这就是为什么。我已经修改了上面的代码,使我相信它们应该是什么样子的。
显式函数定义而不带Ty对联f(应该与标题相同:
代码4:
int (*myFuncDef)(int, int) functionFactory(int n) {
printf("Got parameter %d", n);
int (*functionPtr)(int,int) = &addInt;
return functionPtr;
}代码5: ty胡枝子本身(用于在代码2中简化):
typedef int (*myFuncDef)(int, int) myFuncDef;请注意,这些规则规定了基本规则:返回类型、idenitifer、参数.。
我真的很希望有一个链接,在那里我可以阅读严格的规则,这一切如何解决。一个概述的解释将是很好的,因为等级库没有提供类似的“教程”课程。非常感谢!
也编辑,
注意,这些摘录摘自:C中的函数指针是如何工作的?
发布于 2014-03-07 02:09:42
int (*functionFactory(int n))(int, int) { … }?
Remember these rules for C declares
And precedence never will be in doubt
Start with the Suffix, Proceed with the Prefix
And read both sets from the inside out(当然,除非父母说“先做这件事”。)
所以: functionFactory是
[open paren]
[suffix (int n)] a function taking an `int` argument called `n` that returns
[prefix *] a pointer to
[close paren]
[suffix (int, int)] a function taking two `int` arguments and returning
[prefix int] an integer接下来的{...}给出了functionFactory行为的定义。
(我们可能从名称functionFactory中猜测到,它将返回指向函数的指针。我们也可以查看它的逻辑,看看它返回的类型。)
Typedefs使用与变量声明完全相同的语法,新类型名称替换变量名,(当然)前面是typedef关键字。此工厂返回的类型的函数指针将具有以下类型
int (*functionFromFactory)(int,int); /* oops, forgot parens the first time */因此,这类指针的类型为
typedef int (*PtrToFunctionFromFactory)(int,int);注意,一旦您有了该类型,functionFactory的声明就可以简化为
PtrToFunctionFromFactory functionFactory(int n) {...}(这类函数可能有一个比“”更好的名称,而且这个名称确实应该同时用于typedef和工厂方法的名称,但是由于您没有给我们提供更好的处理方法,所以我不得不使用过于抽象的名称。)
希望这能有所帮助。
发布于 2014-03-07 02:18:02
“由内而外,从右到左”
在声明的名称中,从右到左在该级别是“函数接受一个int返回指针.”,out一个级别“.到一个接受两个int返回int的函数”。
https://stackoverflow.com/questions/22239885
复制相似问题