根据函数名称数组数组的索引调用函数

calling function depending on index of array array of functions' names

本文关键字:数组 函数 索引 调用      更新时间:2023-10-16

在游戏中进行随机操作使它看起来真的很真实...因此,如果字符具有许多capabilities,例如moveworkstudy ...因此,在编程中,这些函数被称为某些条件。我们想要的是一个更随机,更真实的,例如没有条件的动作,但取决于角色随机操作的随机条件。

我想在数组中制作动作(函数),然后声明一个指针,并且程序可以随机生成一个索引,该索引将在该索引上从数组中分配了函数的指针,从数组中分配了相应的函数名称:

#include <iostream>
void Foo()   { std::cout << "Foo"    << std::endl; }
void Bar()   { std::cout << "Bar"    << std::endl; }
void FooBar(){ std::cout << "FooBar" << std::endl; }
void Baz()   { std::cout << "Baz"    << std::endl; }
void FooBaz(){ std::cout << "FooBaz" << std::endl; }

int main()
{
    void (*pFunc)();
    void* pvArray[5] = {(void*)Foo, (void*)Bar, (void*)FooBar, (void*)Baz, (void*)FooBaz};
    int choice;
    std::cout << "Which function: ";
    std::cin >> choice;
    std::cout << std::endl;
    // or random index: choice  = rand() % 5;
    pFunc = (void(*)())pvArray[choice];
    (*pFunc)();

    // or iteratley call them all:
    std::cout << "calling functions iteraely:" << std::endl;
    for(int i(0); i < 5; i++)
    {
        pFunc = (void(*)())pvArray[i];
        (*pFunc)();
    }
    std::cout << std::endl;
    return 0;
}
  • 该程序效果很好,但我只是很好或有其他选择。欢迎每个评论

将函数指针转换为 void*和back绝对没有意义。定义功能指针数组,并将其用作普通数组。该声明的语法在此Q&amp; a中描述(它是C c 中的语法相同)。呼叫的语法是索引器[]之后的直接()应用程序。

void (*pFunc[])() = {Foo, Bar, FooBar, Baz, FooBaz};
...
pFunc[choice]();

演示。

注意:尽管功能指针在C 中起作用,但更灵活的方法是使用std::function对象。