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

3
我想知道如何将一个返回函数作为参数传递给另一个函数,以便我可以使用它的值。
例如:
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
}

谢谢你


1
你想在 motherFunction 中调用传递的函数指针参数吗?你现在有什么问题?只需要直接调用它即可。 - Some programmer dude
2个回答

3

函数指针

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

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

motherFunction(100, childFunction);

 

std::function1

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);

2
您需要将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;
}

1
不用客气。请特别注意M.M.在他的答案中所做的补充,因为它们是一组更灵活的解决方案。我相信你将来会发现它们非常方便。 - Captain Obvlious

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接