函数从结构子级内部调用
Functions call from within struct children
我为程序的"模块"定义了一个结构。我想按模块的名称搜索模块,然后根据模块的名称运行自定义函数。我试图用一个结构来实现这一点:
struct module{
string name;
int number;
string task;
void run(void){
?
}
} Modules[2];
所以现在我想给模块[1]分配名称和编号,并定义一个由模块[1]调用的函数。例如:如果输入等于模块 [0] 的名称,则应调用 function_1((,如果等于模块 [1] 的名称,则应调用 function_2((。
我想为结构的每个子级调用不同的函数。
有没有办法做到这一点?
函数指针听起来像你要找的东西。
您将向结构中添加一个存储函数地址的变量。然后,您可以访问结构数组中的每个项并调用其自定义函数。
例如,尝试一下:
void foo1()
{
printf("foo1");
}
void foo2()
{
printf("foo2");
}
int _tmain(int argc, _TCHAR* argv[])
{
struct module{
string name;
int number;
string task;
void (*pFoo)();
} Modules[2];
Modules[0].pFoo = foo1;
Modules[1].pFoo = foo2;
Modules[0].pFoo(); // calls foo1();
Modules[1].pFoo(); // calls foo2();
return 0;
}
您将看到,您可以为每个Modules[x]
分配指向不同函数的指针,然后您可以在按名称找到所需的Modules[x]
时调用它们。
相关文章:
- join() 失败,如果在线程内部调用 io_context.run()
- 为什么从另一个构造函数内部调用C++构造函数不修改类变量?
- 从动态加载的 dll 内部调用C++函数
- 如何在JNI中从线程内部调用JAVA方法
- 编译在 Python 代码内部调用的 C++ 代码时出错,使用 Boost Python
- 在VC++中从DLLMAIN内部调用D3D的CREATEDEVICE时,它会创建一个死锁(loaderlock?)。有没有办法克服这个问题?最终目标内
- 在成员函数内部调用成员函数
- WM_DESTROY没有在包裹的WndProc内部调用
- 为什么要在JNI内部调用纤维在JVM中抛出堆叠量
- 为什么逗号运算符在运算符[]中打电话给操作员[],而不是在Operator()内部调用
- 在程序集文件内部调用C++函数
- 从Python函数内部调用C++函数
- 使用 Rcpp 从内部调用 R 的 optim 函数C++
- C++ 错误 LNK1120:在静态函数内部调用时有 1 个未解析的外部
- 在应用程序内部调用linux命令行工具
- 当您在设备内部调用cudaMalloc时,实际会发生什么
- 通过传递外部指针或内部调用 new 构造的类,我可以在销毁时天真地删除这个指针吗?
- 在模板成员函数内部调用非模板成员函数
- 如何正确地从运算符构造函数内部调用复制构造函数
- NodeJS Addon从NAN AsyncWorker::Execute内部调用Javascript回调