函数指针的意义是什么? [英] What is the point of function pointers?

查看:38
本文介绍了函数指针的意义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看不到函数指针的效用.我想它在某些情况下可能很有用(毕竟它们存在),但我想不出使用函数指针更好或不可避免的情况.

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()code> 传递另一个函数的地址 g(),并且 f() 调用 g() 来执行某些特定任务.如果你把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.

基本上,这是一种参数化函数的方法:它的某些部分行为没有硬编码到f()中,但进入回调函数.调用者可以通过传递不同的回调函数使 f() 表现不同.一个经典的例子是来自 C 标准库的 qsort(),它将排序标准作为一个指向比较函数的指针.

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 << '
';}
};

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 << '
';}
  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屋!

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