简体   繁体   English

函数指针丢失其值

[英]Function pointer loses its value

I'm trying to implement a menu using a map of chars and function pointers. 我正在尝试使用字符和函数指针的映射来实现菜单。 The program compiles just fine, but when I try to run it the pointers lose their value along the way. 该程序可以很好地进行编译,但是当我尝试运行它时,指针会一直丢失其值。

I'm hoping you guys might know what to do about it. 我希望你们可能知道该怎么做。

I'm using a typedef: 我正在使用typedef:

typedef void (Gui::*userAction)();

and the following map: 和下面的地图:

map<char, userAction> menuOptions;

here is the function registering the pointers: 这是注册指针的函数:

void Gui::registerActions(){
    menuOptions['C'] = &Gui::addCD;
    menuOptions['J'] = &Gui::addJournal;
    menuOptions['N'] = &Gui::addNonFiction;
    menuOptions['F'] = &Gui::addFiction;
    menuOptions['X'] = &Gui::removeObject;
    menuOptions['H'] = &Gui::showHelpMenu;
    menuOptions['S'] = &Gui::search;
    menuOptions['L'] = &Gui::lendItem;
    menuOptions['R'] = &Gui::collectItem;
    menuOptions['Q'] = &Gui::quit;
    cout << menuOptions['C'] << endl; // writes 1
}

I then use a template to interpret user selection and return the correct pointer: 然后,我使用模板来解释用户选择并返回正确的指针:

template<typename Option>
Option getOption(map<char, Option> & options, char choise){
    if(options.count(toupper(choise)) == 1){
        cout << options[choise] << endl; // writes 0
        return options[choise];
    } else {
        throw runtime_error("Choise does not match any alternatives");
    }
}

The choice is made and the functions are called in the following function: 做出选择并在以下函数中调用函数:

void Gui::showRequestMenu(){
    try{
        out << "Choose one of C/J/N/F/X/H(Help)/S/L/R/Q" << endl;
        userAction action = getOption(menuOptions, getChar());
        cout << action ; // writes 0
        (this->*action)(); // crashes the program
    } catch(exception & e){
        out << e.what() << endl;
    }
}

I've tried debugging the program with gdb and it says 我试过用gdb调试程序,它说

program recieved signal SIGSEV, segmentation fault 0x00000000

The problem is probably that you call toupper when checking if the choice is valid and you don't do it later. 问题可能是您在检查选择是否有效时调用了toupper ,后来又不这样做。 The simplest fix seems to be: 最简单的解决方法似乎是:

change: 更改:

userAction action = getOption(menuOptions, getChar());

to: 至:

userAction action = getOption(menuOptions, toupper(getChar()));

and: 和:

if (options.count(toupper(choise)) == 1){

to: 至:

if (options.count(choise) == 1){

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM