一堆函数指针:如何调用函数?

时间:2011-06-30 00:12:07

标签: c++ function stack

我有一堆函数指针(所有void类型&没有参数)。我很难找到如何调用/执行堆栈中的函数?

如果你看一下下面简单的例子,那么everthing compiles&除最后一行外

typedef class InstructionScreen;
typedef void (InstructionScreen::*MemberFuncPtr)();
stack <MemberFuncPtr> instructionStep;              // This is how I declare it. Works
instructionStep.push( &InstructionScreen::step1 );  // This is how I add the member function step(). Works
(*instructionStep.top())();                         // How do I call the function now? This doesn't work

这是我试图编译的整个代码:

class InstructionScreen
{
     public:
         InstructionScreen()
         {
              instructionStep.push( &InstructionScreen::step1 );
              instructionStep.push( &InstructionScreen::step2 );   

              // add timer to call run instructions each 10 seconds        
         }

         void step1()
         {
         }

         void step2()
         {
         }

         void runInstructions()
         {
              if ( !instructionStep.empty() )
              {
                  *(instructionStep.top())(); 
                  instructionStep.pop();
              }
              // else kill timer
         }

     private:
          stack <MemberFuncPtr> instructionStep;   
};

1 个答案:

答案 0 :(得分:2)

您需要一个实例来调用成员函数。试试这个:

InstructionScreen screen;
MemberFuncPtr step = instructionStep.top();
(screen.*step)();

要从另一个成员函数中运行堆栈中的函数,可以使用:

MemberFuncPtr step = instructionStep.top();
(this->*step)();