gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:58:00 24 4
gpt4 key购买 nike

在游戏中做出随机 Action 让它看起来真的很真实......所以如果一个角色有很多capabilitiesmove,work,study...那么在编程中一个函数那些被称为取决于某些条件。我们想要的是一个更随机、更真实的 Action ,没有条件,但角色会根据随机条件采取随机 Action 。

我想在数组中创建 Action (函数),然后声明一个指向函数的指针,程序可以随机生成一个索引,指向函数的指针将在该索引上分配数组中相应的函数名称:

#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对象代替。

关于c++ - 根据函数名称数组的索引调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41173413/

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