7
I am creating classes that represent items in a menu, each item performs an action and I am assigning the action by a function pointer to each instantiated menu item, is this valid by following POO? or there is an easier and more practical way to do this?
Follows code:
class MenuItem{
public:
MenuItem(GLsizei x, GLsizei y, string texto, bool enabled = false);
~MenuItem();
void display();
void setAction(void (*action)());
void runAction();
private:
GLsizei x, y;
string texto;
bool enabled;
void (*action)();
};
void MenuItem::setAction(void (*action)())
{
this->action=action;
}
void MenuItem::runAction()
{
action();
}
Class that instance Menuitem:
class Menu{
public:
Menu(vector<string> itens, GLsizei width, GLsizei heigth);
~Menu();
void selectNext();
void selectPrevious();
MenuItem* getSelectedItem() const;
void display();
private:
MenuItem **itens;
int selectedItem;
int contItens;
GLsizei width, heigth;
};
void function(void){
cout<<"faz alguma coisa"<<endl;
}
Menu::Menu(vector<string> itens, GLsizei width, GLsizei heigth)
:width(width), heigth(heigth)
{
contItens=0;
this->itens=new MenuItem*[itens.size()];
for(string s: itens){
this->itens[contItens++]=new MenuItem(width/2, heigth/2-contItens*30, s);
}
this->itens[selectedItem=0]->setEnabled(true);
this->itens[0]->setAction(function);//aqui eu coloco a ação no primeiro item
}
calling function:
void keyboard(unsigned char key, int x, int y){
if(key=='s')
menu->getSelectedItem()->runAction();
if(key=='d')
menu->selectNext();
if(key=='a')
menu->selectPrevious();
glutPostRedisplay();
}
I only created function
for testing. My idea is to put a method in Menu
which places by means of function pointer the action referenced to each item. But the code itself works, I’m just in doubt if it follows POO and if it’s not so complex?
for menus has the iterator pattern.. then it creates a list, or dictionary to organize the items... I don’t know if this answers your question
– guijob
I am creating my own menu as I am doing an openGL project.
– Ilan Francisco
What kind of application? for example a game. Could you show us some code?
– Andrey França