如何遍历函数[i]()?

0 c++ iterator function

谢谢阅读.我是编程新手,我正在尝试编写一个迭代所有i值的函数.例如,它可能是function3(),然后迭代到随机函数12().这是我到目前为止:

int main()
{
    trigFunction();
    system("pause");
    return 0;
}

void trigFunction()
{
    int i;
    cout << "Welcome to Haris's Unit Circle Fun House!\n";
    srand(time(NULL));
    i = rand()%15;
    for (int x = 1; x < 15; x++)
    {
        functioni(); //This is obviously wrong. Is there way to do this correctly?
        i = rand() % 15;
    }

}
Run Code Online (Sandbox Code Playgroud)

functioni()我在下面定义了文本,例如:

void function3()
{
    cout << "What is 5pi/3 in degrees?\n";
    cin >> answer;
    if (answer == 300)
    {
        cout << "Correct answer!\n";
    }
    else
    {
        cout << "Wrong Answer!\n";
    }
}
void function4()
{
    cout << "What is 3pi/2 in degrees?\n";
    cin >> answer;
    if (answer == 270)
    {
        cout << "Correct answer!\n";
    }
    else
    {
        cout << "Wrong Answer!\n";
    }
}
Run Code Online (Sandbox Code Playgroud)

非常感谢你!

编辑:有没有办法将数组实现到函数结构中?像功能一样?

小智 5

要记住的是,在运行时,函数名称不再存在.至少,不是一种你可以可靠和便携地用来查找功能的形式.

你必须以某种方式将名称(或者,在这种情况下,只是数字)映射到函数.一种简单的方法是使用数组.

typedef void (*pfun)();
pfun functions[] = { function0, function1, function2, function3, function4 };
Run Code Online (Sandbox Code Playgroud)

然后functions[i]();,您可以调用注意,数组索引从0开始,如果i获取不正确的值,事情将会严重破坏.