我想知道如何在定义函数的地方创建函数。然后我可以调用定义的函数。让我举个例子。
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
我希望你明白我在这里想做什么。但我不知道如何将它归结为正确的代码:-)
最佳答案
你需要一个函数指针。如果先typedef
函数指针,使用函数指针会更容易。
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
正如其他答案所建议的那样,您也可以使用函数之类的对象。但这需要运算符重载(即使它对您隐藏)并且通常与模板一起使用。
它提供了更大的灵 active (您可以在将对象传递给函数之前为对象设置一些状态,对象的 operator()
可以使用该状态)但在您的情况下,函数指针可能同样好。
关于c++ - 调用从另一个函数 c++ 定义的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12957218/