在C++中的函數指針可用於這樣的:
#include <iostream>
//defining a type that is a 'function that returns void and takes an int'
typedef void FnPtr(int i);
//this is a 'function that returns void and takes an int'
void AFunction(int i)
{
std::cout << "AFunction Called!";
}
//a function that accepts a pointer to a 'function that returns void and takes an int'
void AFunctionThatTakesAFnPtrAsAnArg(FnPtr* fn)
{
//store the pointer to use "later".
FnPtr* local = fn;
.
.
.
//use it.
local(3);
}
int main(int, char**)
{
AFunctionThatTakesAFnPtrAsAnArg(AFunction);
}
注功能可以是全局的,或一個靜態類成員。如果你想調用一個對象實例的函數,那麼看看這個 - 特別是我的答案! :-) What is a C++ delegate?
編輯:在評論中問道,更適合的問題:
#include <iostream>
typedef void FnPtr();
void AFunction()
{
std::cout << "Animation done";
}
class Sprite
{
public:
void SetFnPointer(FnPtr* fn)
{
m_Fn = fn;
}
void DoAnimation()
{
m_Fn();
}
private:
FnPtr* m_Fn;
};
int main(int, char**)
{
Sprite s;
s.SetFnPointer(AFunction);
s.DoAnimation();
}
謝謝,實際使用功能,將你只需要調用* FN()。還有什麼是本地(3)電話。我對此不熟悉。 – 2012-04-03 10:28:01
此外,爲了適應我的情況,我的函數不會返回任何內容,並且不帶參數,所以我的精靈類將包含typdef void FnPtr(void),然後是void AFunctionThatTakesAFnPtrAsAnArg(FnPtr * fn)。在創建精靈時,我會傳入我將要存儲的函數指針,然後在正確的時間調用AFunctionThatTakesAFnPtrAsAnArg(savedFunctionPtr)。 – 2012-04-03 10:36:18
@馬丁史密斯我已經添加了更多的答案,以適應您的問題;是的,如果你沒有參數,你對typedef是正確的。 HTH。 – 2012-04-03 11:14:53