問題描述
我看不到函數指針的效用.我想它在某些情況下可能很有用(畢竟它們存在),但我想不出使用函數指針更好或不可避免的情況.
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.
這篇關于函數指針的意義是什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!