【问题标题】:Functions call from within struct children从 struct children 中调用函数
【发布时间】:2013-12-12 13:04:09
【问题描述】:

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

struct module{
string name;
int number;
string task;
void run(void){
    ?
    }
} Modules[2];

所以现在我想为 Modules[1] 分配名称和编号,并定义一个由 Modules[1] 调用的函数。 例如: 如果输入为Module[0]的名称,则调用function_1(),如果为Module[1]的名称,则调用function_2()。

我想为结构的每个子级调用不同的函数。

有没有办法做到这一点?

【问题讨论】:

  • 它不是 struct 的子级。我认为您的意思是模块类型的对象。这两个功能有何不同?

标签: c++ function struct


【解决方案1】:

Function Pointers 听起来像您要找的东西。

您将在存储函数地址的结构中添加一个变量。然后,您可以访问结构数组中的每个项目并调用其自定义函数。

试试这个例子:

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] 名称时,您可以调用它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    • 2011-08-14
    • 1970-01-01
    • 2021-12-25
    • 2021-03-27
    相关资源
    最近更新 更多