Answer the question
In order to leave comments, you need to log in
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;
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
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.
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 questionAsk a Question
731 491 924 answers to any question