gpt4 book ai didi

c++ - 从 struct children 中调用的函数

转载 作者:太空狗 更新时间:2023-10-29 21:22:28 25 4
gpt4 key购买 nike

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

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

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

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

有办法吗?

最佳答案

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] 时调用它们你想要的名字。

关于c++ - 从 struct children 中调用的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20544361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com