fork download
  1. #include <vector>
  2. #include <iostream>
  3. class BaseWindow;
  4. class Button
  5. {
  6. public:
  7. typedef void (BaseWindow::*BehaviorPtr)(Button *);
  8.  
  9. private:
  10. BaseWindow* parent;
  11. BehaviorPtr behavior;
  12.  
  13. public:
  14. Button(BaseWindow* parent);
  15. template <typename T> void SetBehavior(T behavior)
  16. {
  17. this->behavior = static_cast<BehaviorPtr>(behavior);
  18. }
  19. void Clicked(/*coords*/)
  20. {
  21. if(1)
  22. {
  23. (parent->*behavior)(this);
  24. }
  25. }
  26. };
  27. class BaseWindow
  28. {
  29. std::vector<Button*> Buttons;
  30. public:
  31. void WindowClicked(/*coords*/)
  32. {
  33. for (std::vector<Button*>::iterator it = Buttons.begin(); it != Buttons.end(); ++it)
  34. {
  35. (*it)->Clicked(/*coords*/);
  36. }
  37. }
  38. void AddButton(Button* butt)
  39. {
  40. Buttons.push_back(butt);
  41. }
  42. };
  43. Button::Button(BaseWindow* parent) : parent(parent), behavior()
  44. {
  45. parent->AddButton(this);
  46. }
  47.  
  48. class UserWindow:public BaseWindow
  49. {
  50. Button MyButton1, MyButton2;
  51. public:
  52. void FunctionForButton1(Button* butt){ std::cout<< "Say Hello, my sweet first button" << std::endl;}
  53. void FunctionForButton2(Button* butt){ std::cout<< "Ha ha ha!!!" << std::endl;}
  54. UserWindow():MyButton1(this), MyButton2(this)
  55. {
  56. MyButton1.SetBehavior(&UserWindow::FunctionForButton1);
  57. MyButton2.SetBehavior(&UserWindow::FunctionForButton2);
  58. }
  59. };
  60. int main()
  61. {
  62. UserWindow w;
  63. w.WindowClicked();
  64. }
  65.  
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Say Hello, my sweet first button
Ha ha ha!!!