返回函数指针类型

返回函数指针类型

本文介绍了返回函数指针类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常发现需要编写返回函数指针的函数.每当我这样做时,我使用的基本格式是:

Often I find the need to write functions which return function pointers. Whenever I do, the basic format I use is:

typedef int (*function_type)(int,int);

function_type getFunc()
{
   function_type test;
   test /* = ...*/;
   return test;
}

然而,在处理大量函数时这会变得很麻烦,所以我不想为每个函数(或每类函数)声明一个 typedef

However this can get cumbersome when dealing with a large number of functions so I would like to not have to declare a typedef for each one (or for each class of functions)

我可以删除 typedef 并将函数中返回的局部变量声明为:int (*test)(int a, int b); 使函数体看起来像这样:

I can remove the typedef and declare the local variable returned in the function as:int (*test)(int a, int b); making the function body look like this:

{
     int (*test)(int a, int b);
     test /* = ...*/;
     return test;
}

但后来我不知道该为函数的返回类型设置什么.我试过了:

but then I do not know what to set for the return type of the function.I have tried:

int(*)(int,int) getFunc()
{
    int (*test)(int a, int b);
    test /* = ...*/;
    return test;
}

但是报告语法错误.如何在不为函数指针声明 typedef 的情况下声明此类函数的返回类型.甚至有可能吗?另请注意,我知道对于每个函数声明 typedef 似乎更清晰,但是,我非常小心地将代码结构化为尽可能干净且易于遵循.我想去掉 typedef 的原因是它们通常只用于声明检索函数,因此在代码中显得多余.

but that reports a syntax error. How do I declare the return type for such a function without declaring a typedef for the function pointer. Is it even possible? Also note that I am aware that it seems like it would be cleaner to declare typedefs, for each of the functions, however, I am very careful to structure my code to be as clean and easy to follow as possible. The reason I would like to eliminate the typedefs is that they are often only used to declare the retrieval functions and therefore seem redundant in the code.

推荐答案

int (*getFunc())(int, int) { … }

这提供了您要求的声明.此外,正如 ola1olsson 所指出的,最好插入 void:

That provides the declaration you requested. Additionally, as ola1olsson notes, it would be good to insert void:

int (*getFunc(void))(int, int) { … }

这表示 getFunc 可能不带任何参数,这有助于避免错误,例如有人无意中编写了 getFunc(x, y) 而不是 getFunc()(x, y).

This says that getFunc may not take any parameters, which can help avoid errors such as somebody inadvertently writing getFunc(x, y) instead of getFunc()(x, y).

这篇关于返回函数指针类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:14