函数指针的用途是什么,我将如何使用它们? [英] What are function pointers used for, and how would I use them?
问题描述
我知道我可以使用函数的指针.
I understand I can use pointers for functions.
有人可以解释为什么要使用它们,以及如何使用?简短的示例代码对我很有帮助.
Can someone explain why one would use them, and how? Short example code would be very helpful to me.
推荐答案
一个简单的例子是这样的:根据业务逻辑,你有一组操作(函数).您有一个散列函数,可以将输入问题减少到业务逻辑函数之一.干净的代码会有一个函数指针数组,您的程序将从输入中推导出该数组的索引并调用它.
A simple case is like this: You have an array of operations (functions) according to your business logic. You have a hashing function that reduces an input problem to one of the business logic functions. A clean code would have an array of function pointers, and your program will deduce an index to that array from the input and call it.
这是一个示例代码:
typedef void (*fn)(void) FNTYPE;
FNTYPE fn_arr[5];
fn_arr[0] = fun1; // fun1 is previously defined
fn_arr[1] = fun2;
...
void callMyFun(string inp) {
int idx = decideWhichFun(inp); // returns an int between 0 and 4
fn_arr[idx]();
}
当然,回调是最常见的用法.示例代码如下:
But of course, callbacks are the most common usage. Sample code below:
void doLengthyOperation(string inp, void (*callback)(string status)) {
// do the lengthy task
callback("finished");
}
void fnAfterLengthyTask(string status) {
cout << status << endl;
}
int main() {
doLengthyOperation(someinput, fnAfterLengthyTask);
}
这篇关于函数指针的用途是什么,我将如何使用它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!