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

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

在游戏中做出随机动作让它看起来真的很真实...... 所以如果一个字符有很多 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* 并返回完全没有意义。定义一个函数指针数组,并将其用作普通数组。 this Q&A 中描述了声明的语法(它适用于 C,但语法在 C++ 中保持不变)。调用的语法是索引器 [].

之后的直接 () 应用程序
void (*pFunc[])() = {Foo, Bar, FooBar, Baz, FooBaz};
...
pFunc[choice]();

Demo.

注意: 尽管函数指针在 C++ 中有效,但更灵活的方法是使用 std::function 对象。