class Menu {
int Option, numofOptions;
void SwitchScreen() {
Console::Clear(); //C++/CLI - clear console
switch(Option) {
case 1: //if option 1 do
break;
// until case numofOptions
}
}
};
I want a custom object of class Menu with variable integer numofOption. What am I going to do to get every case for each option?
I can't help you with C++/CLI... I can only give examples with normal C++.
What you could do is create a small struct to represent each option. Let's call this MenuOption. This will consist of two basic parts:
- a string to indicate what is printed on screen.
- a function callback to get called when that option is selected
Now that we have each option outlined... we can add those options to a Menu class. The menu class can add these options dynamically by putting them in a resizable container, like a vector:
1 2 3 4 5 6 7 8 9 10 11 12
#include <vector>
class Menu
{
std::vector<MenuOption> options;
public:
void addOption( std::string name, std::function<void> clbk )
{
MenuOption o = {name,clbk};
options.push_back(o);
}
Now we can call 'addOption' as many times as we want to add any number of options. To run it, we merely get a selection from the user, and call the appropriate callback depending on whatever option they selected:
void run()
{
// print the options to the user
cout << "Please select an option:\n";
for(unsigned x = 0; x < options.size(); ++x)
cout << " " << (x+1) << ") " << options[x] << '\n';
// get the option they chose:
int selection;
cin >> selection;
// assuming the option is valid (read: I'm not doing that here! You will
// want to check to make sure they didn't input something stupid. I'm
// omitting that to keep the example simple)
//
// So yeah.. assuming it's valid... just call the appropriate callback:
options[selection-1].callback();
}
};
And there you have it. Now to use it, all you have to do is give it some options and call run: