c++ - 调用从另一个函数 c++ 定义的函数

标签 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

我希望你明白我在这里想做什么。但我不知道如何将它归结为正确的代码:-)

最佳答案

你需要一个函数指针。如果先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/

相关文章:

c++ - 查找包含值的单元格的索引并突出显示 QTableView 中的所有这些单元格

c++ - 我怎样才能克服cuda中的内存分配

c++ - 如何使用 C++ 在 LUA 中编写具有对话和菜单的交互式 NPC 脚本?

c++ - 我想读入一个文本文件中的所有内容(但文本文件中只有一个double值),转换为double并返回值

c++ - 如果使用嵌套命名空间,如何转发声明 C++ 结构?

C++ - 使用 `this` 在类级别初始化成员与在构造函数中使用 `this` 之间有什么区别吗?

c++ - 管道优化,这样做有什么意义吗?

c++ - 无锁读写器

c++ - 如何让我的 mousehook 从单独的线程回调? C++

c++ - 为什么 c++ double 会将自己限制为小数点后 5 位?