S E*_*S E 54 c syntax types function-pointers
我经常发现需要编写返回函数指针的函数.每当我这样做,我使用的基本格式是:
typedef int (*function_type)(int,int);
function_type getFunc()
{
function_type test;
test /* = ...*/;
return test;
}
Run Code Online (Sandbox Code Playgroud)
但是,在处理大量函数时,这会很麻烦,所以我不想为每个函数声明一个typedef(或者对于每个函数类)
我可以删除typedef并声明函数中返回的局部变量:
int (*test)(int a, int b);使函数体看起来像这样:
{
int (*test)(int a, int b);
test /* = ...*/;
return test;
}
Run Code Online (Sandbox Code Playgroud)
但后来我不知道该函数的返回类型设置了什么.我试过了:
int(*)(int,int) getFunc()
{
int (*test)(int a, int b);
test /* = ...*/;
return test;
}
Run Code Online (Sandbox Code Playgroud)
但是报告语法错误.如何在不声明函数指针的typedef的情况下声明此类函数的返回类型.它甚至可能吗?另请注意,我知道为每个函数声明typedef似乎更干净,但是,我非常小心地将我的代码构造成尽可能干净且易于遵循.我想消除typedef的原因是它们通常只用于声明检索函数,因此在代码中看起来是多余的.
Eri*_*hil 60
int (*getFunc())(int, int) { … }
Run Code Online (Sandbox Code Playgroud)
这提供了您要求的声明.另外,正如ola1olsson指出的那样,最好插入void:
int (*getFunc(void))(int, int) { … }
Run Code Online (Sandbox Code Playgroud)
这说明getFunc可能不会采取任何参数,这可以帮助避免错误,如有人无意中写getFunc(x, y)而不是getFunc()(x, y).
您可以做以下事情:
int foo (char i) {return i*2;}
int (*return_foo()) (char c)
{
return foo;
}
Run Code Online (Sandbox Code Playgroud)
但是上帝,我希望我永远不必调试你的代码....
| 归档时间: |
|
| 查看次数: |
42493 次 |
| 最近记录: |