2012-10-18 115 views
1

我想知道,如何製作一個函數來定義一個函數。然後我可以調用已定義的函數。讓我試一試。調用從另一個函數定義的函數C++

void funcToCall() { 
    std::cout<<"Hello World"<<std::endl; 
} 

void setFuncToCall(void func) { 
    //Define some variable with func 
} 

void testFuncCall() { 
    //Call function that has been defined in the setFuncToCall 
} 

setFuncToCall(funcToCall()); //Set function to call 
testFuncCall(); //Call the function that has been defined 

我希望你明白我在這裏要做的。但我不知道如何將它放到正確的代碼:-)

+0

你需要函數指針 –

+0

或std :: function – marcinj

回答

4

您需要一個函數指針。如果你首先使用函數指針,它會更容易。

typedef void (*FuncToCallType)(); 

FuncToCallType globalFunction; // a variable that points to a function 

void setFuncToCall(FuncToCallType func) { 
    globalFunction = func; 
} 

void testFuncCall() { 
    globalFunction(); 
} 

setFuncToCall(funcToCall); //Set function to call,NOTE: no parentheses - just the name 
testFuncCall(); //Call the function that has been defined 

其他答案建議你也可以使用像函數這樣的對象。但是這需要運算符重載(即使它對你來說仍然是隱藏的),並且通常與模板一起使用。它提供了更多的靈活性(可以在將對象傳遞給函數之前設置對象的某個狀態,對象的operator()可以使用該狀態),但在您的情況下,函數指針可能同樣好。

+0

這個工作對我來說很完美!非常感謝你的回答! :-) – PeterBechP

2
函數指針

C語法是有點怪異,但在這裏我們去:

// this is a global variable to hold a function pointer of type: void (*)(void) 
static void (*funcp)(void); 
// you can typedef it like this: 
//typedef void (*func_t)(void); 
// - now `func_t` is a type of a pointer to a function void -> void 

// here `func` is the name of the argument of type `func_t` 
void setFuncToCall(void (*func)(void)) { 
// or just: void setFuncToCall(func_t func) { 
    //Define some variable with func 
    ... 
    funcp = func; 
} 

void testFuncCall(void) { 
    //Call function that has been defined in the setFuncToCall 
    funcp(); 
} 

setFuncToCall(funcToCall); // without() ! 
testFuncCall(); 
2

要使用什麼是回調,並且已經回答了她:Callback functions in c++

我會建議你使用std::tr1::function(廣義回調)

+0

是的,我沒有想過它,這是C++比我的答案更好的選擇。 –