jeudi 30 mars 2017

What is the simplest way in C++ to get and continue to call a class method, the type of which the current class does not know?

Example: Suppose we are developing a simple graphical interface:

We have windows and controls. What do we want:

  • There is a base window class that implements the GUI functionality hidden from the user.
  • From the base window, the user inherits a specific window.
  • There is a class of a button, an instance of which the user can add to his window.
  • The user can transfer the method of his window, and he will be executed when clicking this button.

I'm interested in how to reach the last point.

Kind of pseudo-code:

class BaseWindow;

class Button
{
public:
            Button(BaseWindow* parent)
            {
                        parent->AddButton(this);
            }

            void SetBehavior(/*Owners pointer and owner's methos*/)
            {
                        /* Save Owner pointer and owner's method*/
            }

            void Clicked(/*coords*/)
            {
                        if(/*coords == my coords*/)
                        {
                                    /*Call Owner's method*/
                        }
            }
};

class BaseWindow
{
            vector<Button*> Buttons;

            WindowClicked(/*coords*/)
            {
                    for(auto i:Buttons)
                    {
                                i->Clicked(/*coords*/);
                    }
            }

public:
            void AddButton(Button* butt)
            {
                            Buttons<<butt;
            }

};

class UserWindow:public BaseWindow
{
            Button MyButton;
public:
            void FunctionForButton(Button* butt){ cout<<"Say Hello, my sweet button";}

            UserWindow():MyButton(this)
            {
                        MyButton.SetBehavior(/*Put here my Function for Button and my pointer*/);
            }
};

Aucun commentaire:

Enregistrer un commentaire