什么是函数指针的地步? [英] What is the point of function pointers?
问题描述
我无法看到函数指针的效用。我想这可能是在某些情况下(他们的存在,毕竟)是有用的,但我不认为它是好还是不可避免的要使用的函数指针的情况。
I have trouble seeing the utility of function pointers. I guess it may be useful in some cases (they exist, after all), but I can't think of a case where it's better or unavoidable to use a function pointer.
你能给良好的使用功能指针(在C或C ++)?一些例子
Could you give some example of good use of function pointers (in C or C++)?
推荐答案
大多数示例归结为 回调的:你调用一个函数 F( )
通过另一个函数的地址克()
和 F()
调用克()
对于一些特定的任务。如果你通过 F()
地址 H()
来代替,那么 F()
将回调 H()
来代替。
Most examples boil down to callbacks: You call a function f()
passing the address of another function g()
, and f()
calls g()
for some specific task. If you pass f()
the address of h()
instead, then f()
will call back h()
instead.
基本上,这是一种方法, 参数多态的功能:其行为的某些部分不硬coded到 F( )
,但进入回调函数。呼叫者可以让 F()
通过传递不同的回调函数表现不同。一个典型的是的qsort()
向变更后承受其排序标准为指针,以一个比较函数C标准库。
Basically, this is a way to parametrize a function: Some part of its behavior is not hard-coded into f()
, but into the callback function. Callers can make f()
behave differently by passing different callback functions. A classic is qsort()
from the C standard library that takes its sorting criterion as a pointer to a comparison function.
在C ++中,这通常使用做的(又称仿函数)。这些都是重载函数调用操作的对象,所以你可以打电话给他们,好像他们是一个函数。例如:
In C++, this is often done using function objects (also called functors). These are objects that overload the function call operator, so you can call them as if they were a function. Example:
class functor {
public:
void operator()(int i) {std::cout << "the answer is: " << i << '\n';}
};
functor f;
f(42);
这背后的想法是,不像函数指针,一个功能对象可以携带不仅一种算法,而且数据
The idea behind this is that, unlike a function pointer, a function object can carry not only an algorithm, but also data:
class functor {
public:
functor(const std::string& prompt) : prompt_(prompt) {}
void operator()(int i) {std::cout << prompt_ << i << '\n';}
private:
std::string prompt_;
};
functor f("the answer is: ");
f(42);
的另一个优点是,它是有时容易直列调用函数比通过函数指针调用对象。这就是为什么用C排序的理由++有时比在C
Another advantage is that it is sometimes easier to inline calls to function objects than calls through function pointers. This is a reason why sorting in C++ is sometimes faster than sorting in C.
这篇关于什么是函数指针的地步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!