想象一下,一个功能myFunctionA与参双和int:如何声明一个返回函数指针的函数?
myFunctionA (double, int);
该函数返回一个函数指针:
char (*myPointer)();
如何申报用C这个功能呢?
想象一下,一个功能myFunctionA与参双和int:如何声明一个返回函数指针的函数?
myFunctionA (double, int);
该函数返回一个函数指针:
char (*myPointer)();
如何申报用C这个功能呢?
void (*fun(double, int))();
按照right-left-rule,fun
是double, int
返回一个指针与不确定参数的函数的函数返回void
。
编辑:This是该规则的另一个链接。编辑2:这个版本只是为了紧凑和表明它确实可以完成。
这里使用typedef确实很有用。但不是指针,而是到函数类型本身。
为什么?因为可以将它用作一种原型,所以确保函数确实匹配。并且因为指针的身份保持可见。
所以一个好的解决办法是
typedef char specialfunc();
specialfunc * myFunction(double, int);
specialfunc specfunc1; // this ensures that the next function remains untampered
char specfunc1() {
return 'A';
}
specialfunc specfunc2; // this ensures that the next function remains untampered
// here I obediently changed char to int -> compiler throws error thanks to the line above.
int specfunc2() {
return 'B';
}
specialfunc * myFunction(double value, int threshold)
{
if (value > threshold) {
return specfunc1;
} else {
return specfunc2;
}
}
typedef
是你的朋友:
typedef char (*func_ptr_type)();
func_ptr_type myFunction(double, int);
给予好评“因为我从来没有想到这一点!谢谢。 –
做一个typedef:
typedef int (*intfunc)(void);
int hello(void)
{
return 1;
}
intfunc hello_generator(void)
{
return hello;
}
int main(void)
{
intfunc h = hello_generator();
return h();
}
upvote here也出于同样的原因和相同的感谢。 –
char * func() { return 's'; }
typedef char(*myPointer)();
myPointer myFunctionA (double, int){ /*Implementation*/ return &func; }
感谢您的编辑,但我已经给您接受+1。那正是我在寻找的。 –
Thx。我只是想a)要清楚,b)给出良好实践的提示。 – glglgl