我正在尝试使用字符和函数指针的映射来实现菜单。该程序可以很好地进行编译,但是当我尝试运行它时,指针会一直丢失其值。
我希望你们可能知道该怎么做。
我正在使用typedef:
typedef void (Gui::*userAction)();
和下面的 map :
map<char, userAction> menuOptions;
这是注册指针的函数:
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
}
然后,我使用模板来解释用户选择并返回正确的指针:
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");
}
}
做出选择并在以下函数中调用函数:
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;
}
}
我试过用gdb调试程序,它说
program recieved signal SIGSEV, segmentation fault 0x00000000
最佳答案
问题可能是您在检查选择是否有效时调用了toupper
,以后又不这样做。最简单的解决方法似乎是:
更改:
userAction action = getOption(menuOptions, getChar());
至:
userAction action = getOption(menuOptions, toupper(getChar()));
和:
if (options.count(toupper(choise)) == 1){
至:
if (options.count(choise) == 1){