017
15.03.2005, 16:58 Uhr
0xdeadbeef
Gott (Operator)
|
Ich würd das ganze über eine vernünftige Vererbungsstruktur machen. Eben mal hingekladdet sieht das so aus:
C++: |
#include <iostream> #include <sstream> #include <string> #include <vector>
class menu_choice { public: virtual ~menu_choice() { };
virtual std::string const &get_description() const = 0; virtual void operator()() const = 0; };
class menu : public menu_choice { public: menu(std::string const &banner = "", std::string const &description = "") : banner_ (banner), description_(description){ }
void set_banner (std::string const &b) { banner_ = b; } void set_description(std::string const &d) { description_ = d; }
void push_back(menu_choice *mc) { choices_.push_back(mc); }
virtual std::string const &get_description() const { return description_; }
virtual void operator()() const { std::string zeile; std::stringstream sstr; int choice;
std::cout << banner_ << std::endl;
for(int i = 0; i < choices_.size(); ++i) std::cout << i + 1 << ") " << choices_[i]->get_description() << std::endl;
do { sstr.clear();
std::getline(std::cin, zeile); sstr.str(zeile); sstr >> choice; } while(!sstr || choice < 1 || choice > choices_.size());
(*choices_[choice - 1])(); }
private: std::string banner_; std::string description_; std::vector<menu_choice*> choices_; };
class hooray : public menu_choice { public: virtual std::string const &get_description() const { return hooray_; }
virtual void operator()() const { std::cout << "Hooray!" << std::endl; }
private: static const std::string hooray_; };
std::string const hooray::hooray_ = "hooray!";
class main_menu : public menu { public: main_menu() { menu1 = new menu("Foo", "foo"); menu2 = new menu("Bar", "bar"); menu3 = new menu("Baz", "baz");
h = new hooray;
menu3->push_back(h);
menu2->push_back(h); menu2->push_back(h); menu2->push_back(menu3);
menu1->push_back(menu2); menu1->push_back(menu3); menu1->push_back(h);
push_back(menu1); push_back(menu3); }
~main_menu() { delete menu1; delete menu2; delete menu3; delete h; }
private: menu *menu1, *menu2, *menu3; hooray *h; };
int main() { main_menu m; m(); }
|
...wobei das sicher noch verbessert werden kann. -- Einfachheit ist Voraussetzung für Zuverlässigkeit. -- Edsger Wybe Dijkstra |