如何将返回函数中的值作为另一个函数的参数传递,在c++中使用它,然后适当地调用它

How to pass a value in a return function as an argument on another function, use it in and then call it appropriately C++?

本文关键字:函数 调用 然后 c++ 参数传递 返回 另一个      更新时间:2023-10-16

我想知道如何将返回函数作为参数传递给另一个函数,以便我可以使用它的值。

的例子:

int childFunction(int a, int b)
{
    int c;
    c = a + b;
    return c;
}
void motherFunction(int d, int (childFunction)(int a, int b))
{
    //some operation example
}

谢谢

函数指针

使用*创建一个指向函数的指针:

void motherFunction(int d, int (*f)(int, int))
{
    int y = f(1, 2);
}
...
motherFunction(100, childFunction);

,

<

std::函数一口> 1

void motherFunction(int d, const std::function<int(int,int)> &f)
{
    int y = f(1, 2);
}
...
motherFunction(100, childFunction);

,

基于模板的

template <typename F>
void motherFunction(int d, const F &f)
{
    int y = f(1, 2);
}
...
motherFunction(100, childFunction);

您需要将childFunction参数声明为函数指针。

void motherFunction(int d, int (*func)(int, int))
{
    func(d, 0);
}

int childFunction(int a, int b)
{
    int c;
    c = a + b;
    return c;
}
int main()
{
    motherFunction(1, childFunction);
    return 0;
}