C++:How to pass reference-to-function into another function?

…衆ロ難τιáo~ 提交于 2019-11-29 18:21:41

问题


I have been reading about function pointers and about using them as parameters for other functions. My question is how would you pass a function by reference without using pointers? I have been trying to find the answer on the Internet but I haven't found a good answer. I know that you can pass variables by reference like this: void funct(int& anInt);. How would you do something similar to this but instead of a reference to a variable a reference to a function was the parameter? Also how would you use a reference to the function in a function body?


回答1:


#include <iostream>
using namespace std;

void doCall( void (&f)(int) )
{
    f( 42 );
}

void foo( int x )
{
    cout << "The answer might be " << x << "." << endl;
}

int main()
{
    doCall( foo );
}

Cheers & hth.,



来源:https://stackoverflow.com/questions/7142883/chow-to-pass-reference-to-function-into-another-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!