根据函数名称数组数组的索引调用函数
calling function depending on index of array array of functions' names
在游戏中进行随机操作使它看起来真的很真实...因此,如果字符具有许多capabilities
,例如move
,work
,study
...因此,在编程中,这些函数被称为某些条件。我们想要的是一个更随机,更真实的,例如没有条件的动作,但取决于角色随机操作的随机条件。
我想在数组中制作动作(函数),然后声明一个指针,并且程序可以随机生成一个索引,该索引将在该索引上从数组中分配了函数的指针,从数组中分配了相应的函数名称:
#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
对象。
相关文章:
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 打印 2D 动态数组 c++ 函数
- C++数组函数
- 在数组函数指针中调用void
- 数组函数似乎没有找到最大值
- 使用数组函数和循环求解伪元编码|C
- 在头文件中的函数原型中获取指针数组:函数声明为 void
- 数组函数错误输出
- 读取文件,然后创建数组函数C++
- 指针数组函数参数-奇怪的行为
- 二维数组 - 函数
- "return"没有从数组函数返回正确的值
- 数组函数问题
- 数组函数的大小返回 int 的大小而不是数组
- 从数组函数中删除元素
- 如何从C++中最好地调用具有C99风格数组函数签名的函数
- 追加/打印/插入数组c++函数问题
- 如何将数组函数转换为指针函数
- 多维数组函数输出垃圾
- C++:数组函数的递归最大值