本文介绍了从函数指针数组调用C ++函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using function pointers stored in an array with a typedef defining the pointer and I'm a little lost on how I'm supposed to call the function.

这是Menu.h部分:

here's the Menu.h part:

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

FunctionPointer* m_funcPointers;

这是Menu.cpp部分:

here's the Menu.cpp part:

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是用作索引的整数.我不确定如何实际调用该函数,因为上面的行给了我这个错误:

m_currentButton is an integer used as the index. I'm not sure how to actually call the function as the above line gives me this error:

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

视觉工作室给我这个:

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

我不知道如何解决上述问题,也不知道是由于调用函数还是存储函数.预先感谢.

I don't know how to solve the above problem and whether it's due to how I'm calling the function or how I'm storing it.Thanks in advance.

推荐答案

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

You call a function pointer in an array the same way as you would call a function that is not in an array.

您的问题不是如何在数组中调用函数指针.您试图像调用成员函数指针那样调用成员函数指针的问题.

Your problem isn't how to call a function pointer in an array as such. Your problem that you're trying to call a member function pointer as if it were a function pointer.

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

You can call a member function pointer like this:

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

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

Edit for the new example code: Since you're in a member function, perhaps you intend to call the member function pointer on this:

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

如果您觉得语法难以阅读,我不会怪您.相反,我建议改用 std :: invoke (自C ++-17起可用):

If you find the syntax painful to read, I won't blame you. Instead, I'll suggest using std::invoke instead (available since C++-17):

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

这篇关于从函数指针数组调用C ++函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 20:47
查看更多