gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:48:32 25 4
gpt4 key购买 nike

我有一堆函数指针(都是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com