C++从函数指针数组调用函数
C++ Calling Functions from an Array of Function Pointers
我正在使用存储在数组中的函数指针,其中 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);
相关文章:
- 函数调用中参数的顺序重要吗
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 变量没有改变?通过向量的函数调用
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 模板函数调用
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 析构函数调用
- 成员函数调用和C++对象模型
- 使用共享指针的函数调用,其对象应为 const
- C++:编译时检查匹配的函数调用对?
- 函数调用C++中的参数太少
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 返回指向对象的指针的函数调用是否为 prvalue?
- C++ 如何重载 [] 运算符并进行函数调用
- 代码的效率. 转到和函数调用
- 是同一作用域的函数部分中的函数调用
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- 类型擦除的std::function与虚拟函数调用的开销