注册 登录
编程论坛 C++教室

函数的调用顺序

mfkblue 发布于 2009-09-05 16:25, 418 次点击
void A(){}
void B(){}
void C(){}
for(int i=0;i<10;i++)
{
    A();
    B();
    C();
}
如上面的代码,我需用这三个函数10次,每次调用的顺序都会变,可以是ABC,也可能是CBA;如何才能控制循环里函数的先后执行顺序?
3 回复
#2
mfkblue2009-09-05 16:27
写三个switch,每个switch函数里还得写把三个复制写一遍?
#3
最左边那个2009-09-05 22:44
或许,可以给A B C 三个函数加个标识,利用标识来控制
#4
serious2009-09-06 23:32
你可以用函数的指针 :
程序代码:
#include <string>
#include <sstream>
#include <iostream>
#include <map>
using namespace std;
void A()
{
    cout << "In A" << endl;
}
void B()
{
    cout << "In B" << endl;
}
void C()
{
    cout << "In C" << endl;
}
void invoke(string order)
{
    static map<string const, void(*)()> functions;
    functions["A"] = A;
    functions["B"] = B;
    functions["C"] = C;
    istringstream iss(order);
    string functionName;
    while (iss >> functionName)
    {
        functions[functionName]();
    }
}
int main()
{
    invoke("A B C");
    cout << "---" << endl;
    invoke("C B A");
}

1