C ++:如何将引用到函数传递到另一个函数? [英] C++:How to pass reference-to-function into another function?

查看:132
本文介绍了C ++:如何将引用到函数传递到另一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读函数指针,并将它们用作其他函数的参数。我的问题是如何通过引用传递函数而不使用指针?我一直试图在互联网上找到答案,但我没有找到一个好的答案。我知道你可以像这样引用变量: void funct(int& anInt); 。你会如何做类似于此的事情,而不是对变量的引用,而是对参数的引用?另外你如何使用函数体中的函数引用?

包括< iostream>
使用namespace std;

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

void foo(int x)
{
cout<< 答案可能是<< x<< << ENDL;
}

int main()
{
doCall(foo);
}

Cheers& hth。,


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?

解决方案

#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.,

这篇关于C ++:如何将引用到函数传递到另一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆