如何使函数返回指向函数的指针?(C++)

64 c++ function-pointers return-value

我正在尝试创建一个带字符的函数,然后根据字符的内容返回一个指向函数的指针.我只是不确定如何使函数返回指向函数的指针.

eri*_*len 95

int f(char) {
    return 0;
}

int (*return_f())(char) {
    return f;
}
Run Code Online (Sandbox Code Playgroud)

不,说真的,使用typedef :)

  • 您能否详细说明“使用typedef”? (2认同)
  • 提供快捷方式“typedef int (*ifc)(char);”并将其用作函数中的返回类型:“ifc return_f();” (2认同)

小智 68

#include <iostream>
using namespace std;

int f1() {
    return 1;
}

int f2() {
    return 2;
}

typedef int (*fptr)();


fptr f( char c ) {
    if ( c == '1' ) {
        return f1;
    }
    else {
        return f2;
    }
}

int main() {
    char c = '1';
    fptr fp = f( c );
    cout << fp() << endl;
}
Run Code Online (Sandbox Code Playgroud)

  • @qed:不.你可以取消引用它,但完全没有这样做.无论如何,常用​​功能已经内部指针. (3认同)
  • 我想知道为什么这有效。难道我们不应该首先尊重函数指针,即“cout &lt;&lt; (*fp)() &lt;&lt; endl;”吗? (2认同)

sea*_*n e 18

为函数签名创建typedef:

typedef void (* FuncSig)(int param);
Run Code Online (Sandbox Code Playgroud)

然后将您的函数声明为返回FuncSig:

FuncSig GetFunction();
Run Code Online (Sandbox Code Playgroud)


Sup*_*Jon 7

在 C++11 中,您可以使用尾随返回类型来简化语法,例如假设一个函数:

int c(int d) { return d * 2; }
Run Code Online (Sandbox Code Playgroud)

这可以从一个函数返回(需要一个双精度来表示):

int (*foo(double e))(int)
{
    e;
    return c;
}
Run Code Online (Sandbox Code Playgroud)

使用尾随返回类型,这变得更容易阅读:

auto foo2(double e) -> int(*)(int)
{
    e;
    return c;
}
Run Code Online (Sandbox Code Playgroud)


Jar*_*d42 7

假设int f(char)ret_f返回&f

C++98/C++03兼容方式:

从 C++11 开始,我们还有:

C++14 补充说:


小智 6

以下是不使用 typedef 的方法:

int c(){ return 0; }

int (* foo (void))(){  //compiles
return c;
}
Run Code Online (Sandbox Code Playgroud)


VIN*_*TIC 5

返回函数的语法:

return_type_of_returning_function (*function_name_which_returns_function)(actual_function_parameters) (returning_function_parameters)
Run Code Online (Sandbox Code Playgroud)

例如:考虑如下需要返回的函数,

void* (iNeedToBeReturend)(double iNeedToBeReturend_par)
{
}
Run Code Online (Sandbox Code Playgroud)

现在,可以将iNeedToBeReturend函数返回为

void* (*iAmGoingToReturn(int iAmGoingToReturn_par))(double)
{
   return iNeedToBeReturend;
}
Run Code Online (Sandbox Code Playgroud)

经过3年的专业编程生涯,我觉得学习这个概念非常糟糕。

等待下来等待解引用函数指针的好处。

C ++面试题

返回函数指针的函数示例是 c ++中动态库中的dlopen