C++从函数指针数组调用函数

C++ Calling Functions from an Array of Function Pointers

本文关键字:函数 调用 数组 指针 C++      更新时间:2023-10-16

我正在使用存储在数组中的函数指针,其中 typedef 定义了指针,我对应该如何调用函数有点迷茫。

这是Menu.h部分:

typedef void( Menu::*FunctionPointer )();
FunctionPointer* m_funcPointers;

这是菜单.cpp部分:

Menu::Menu()
: m_running( true )
, m_frameChanged( true )
, m_currentButton( 0 )
, m_numOfButtons( k_maxButtons )
, m_menuButtons( new MenuButton[k_maxButtons] )
, m_nullBtn( new MenuButton( "null", Vector2( -1, -1 ) ) )
, m_frameTimer( 0 )
, m_funcPointers( new FunctionPointer[k_maxButtons])
{
m_timer.start();
clearButtons();
mainMenu();
}
void Menu::enterButton()
{
m_funcPointers[m_currentButton]();//Error here
}
void Menu::mainMenu()
{
m_funcPointers[0] = &Menu::btnPlay;
m_menuButtons[0] = MenuButton("Play", Vector2(0, 0));
m_funcPointers[1] = &Menu::btnHiScores;
m_menuButtons[1] = MenuButton("HiScores", Vector2(0, 1));
m_funcPointers[2] = &Menu::btnExit;
m_menuButtons[2] = MenuButton("Exit", Vector2(0, 2));
}
void Menu::btnPlay()
{
StandardGame* game = new StandardGame();
game->play();
delete game;
}

m_currentButton 是用作索引的整数。我不确定如何实际调用该函数,因为上面的行给了我这个错误:

**C2064 term does not evaluate to a function taking 0 arguments**

和视觉工作室给我这个:

expression preceding parentheses of apparent call must have (pointer-to-) function type

我不知道如何解决上述问题,以及是由于我如何调用函数还是如何存储它。 提前谢谢。

从函数指针数组调用函数

调用数组中的函数指针的方式与调用不在数组中的函数的方式相同。

您的问题不在于如何在数组中调用函数指针。您尝试调用成员函数指针的问题,就好像它是函数指针一样。

您可以像这样调用成员函数指针:

Menu menu; // you'll need an instance of the class
(menu.*m_funcPointers[m_currentButton])();

编辑新的示例代码: 由于您在成员函数中,也许您打算在this上调用成员函数指针:

(this->*m_funcPointers[m_currentButton])();

如果你觉得语法读起来很痛苦,我不会责怪你。相反,我建议改用std::invoke(从 C++-17 开始可用(:

std::invoke(m_funcPointers[m_currentButton], this);