A
A
AleksG02018-06-05 09:47:58
OOP
AleksG0, 2018-06-05 09:47:58

C++ native event handler for individual class instance?

Good day.
I'm starting to program in C ++, I needed to make different handlers for different objects for an event of the same type, something like "onClick".
Something like this on "pascale" (in Delphi7):

{ Создание объекта }
Button:=TButton.Create(Form1);
{Обработчик событий}
procedure Button1Click;
begin
end;
{ Привязка обработчика }
Button.OnClick:=Button1Click;

Is it possible to do this in C++ so that the fields of the object can be used inside the function?
Did so far
class TButton{
public:
void (*onClick)(void);
};
/* обработчик - простая функция (без доступа к полям объекта) */
void onClick1(void){
  // что-то
}

TButton *b = new TButton();
b->onClick = onClick1;
b->onClick();// Вызов

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
res2001, 2018-06-05
@AleksG0

Usually this is done through inheritance, rather than saving function pointers. Then you will have full access to the class members from the methods.
Those. you have a base class TButton with a virtual onClick function. You make your own class, whose parent is TButton, override onClick. Profit.
This is how many GUI libraries like Qt, MFC, etc. are arranged.

A
AleksG0, 2018-06-05
@AleksG0

Did I understand you correctly?

class TButton {
public:
    virtual void onClick(void)=0;
};

class TButton1 : public TButton {
public:
    void onClick(void);
};

void TButton1::onClick(void){
    cout<<"click to button1";
}

int main()
{
    TButton *btn = new TButton1(); 
    btn->onClick();
    return 0;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question