c++ - 一堆函数指针 : how to call the function?

标签 c++ function stack

我有一堆函数指针(都是 void 类型且没有参数)。我很难弄清楚如何调用/执行堆栈中的函数?

如果您查看下面的简单示例,除了最后一行之外的所有内容都可以编译和工作

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;   
};

最佳答案

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

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

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

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

关于c++ - 一堆函数指针 : how to call the function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6528678/

相关文章:

javascript - 如何从回调函数返回值

javascript - 变量在 Javascript 函数中用作参数之前是否应该先声明?

c++ - 如何在做方程式时在 C++ 中开始换行

c++ - 我可以依赖函数范围的静态变量来调用程序关闭期间调用的方法吗?

c - C传递结构作为函数参数

java - 使用 GenericQueue 以相反的顺序打印用户输入的单词。 java

c - C 中的锯齿状数组 (3D)

c - 在 Fedora 21 中启用 Stack Smashing

c++ - 使用这个切片我的对象

c++ - 用于嵌入式设备的 Qt Quick 控件 2.0