函数从结构子级内部调用

Functions call from within struct children

本文关键字:内部 调用 结构 函数      更新时间:2023-10-16

我为程序的"模块"定义了一个结构。我想按模块的名称搜索模块,然后根据模块的名称运行自定义函数。我试图用一个结构来实现这一点:

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]时调用它们。