zoukankan      html  css  js  c++  java
  • 24.函数信号机制(本质上就是函数指针)

      1 #define _CRT_SECURE_NO_WARNINGS
      2 #include <iostream>
      3 #include <boost/bind.hpp>
      4 #include <boost/function.hpp>
      5 #include <boost/signals2.hpp>//信号
      6 #include <cstdlib>
      7 
      8 using namespace std;
      9 using namespace boost;
     10 
     11 //信号模拟
     12 class button
     13 {
     14 public:
     15     void connect(void(*f)(int, int));
     16     void Onclick();
     17 private:
     18     void(*pfun)(int, int);
     19 };
     20 
     21 void button::Onclick()
     22 {
     23     this->pfun(10, 20);
     24 }
     25 
     26 void button::connect(void(*f)(int, int))
     27 {
     28     //初始化函数指针
     29     this->pfun = f;
     30 }
     31 
     32 void run(int x, int y)
     33 {
     34     cout << x << y << endl;
     35 }
     36 
     37 void main1()
     38 {
     39     button b1;
     40     b1.connect(run);
     41     while (1)
     42     {
     43         system("pause");
     44         b1.Onclick();
     45     }
     46     cin.get();
     47 }
     48 
     49 
     50 class Button
     51 {
     52     //简化定义
     53 private:
     54     //函数
     55     typedef signals2::signal<void(int, int)> Onclick;
     56     //链接
     57     typedef signals2::signal<void(int, int)>::slot_type OnSlottype;
     58 
     59 public:
     60     //链接
     61     signals2::connection connect(const OnSlottype &type);
     62     //解除链接
     63     void disconnect0(const signals2::connection &type);
     64     //按钮按下
     65     void OnBnclick();
     66 
     67 public:
     68     signals2::connection connect_;//代表链接
     69     Onclick onclick_;//代表链接的函数
     70 };
     71 
     72 //绑定到onclick_
     73 signals2::connection Button::connect(const OnSlottype &type)
     74 {
     75     return connect_ = onclick_.connect(type);//链接
     76 }
     77 
     78 //解除链接
     79 void Button::disconnect0(const signals2::connection &type)
     80 {
     81     //关闭一个链接
     82     onclick_.disconnect(connect_);
     83     //关闭所有的链接
     84     //onclick_.disconnect_all_slots();
     85 }
     86 
     87 //按钮按下
     88 void Button::OnBnclick()
     89 {
     90     onclick_(10, 20);
     91 }
     92 
     93 
     94 void main()
     95 {
     96     Button btn;
     97     btn.connect(&run);
     98     while (1)
     99     {
    100         system("pause");
    101         btn.OnBnclick();
    102         btn.disconnect0(btn.connect_);
    103     }
    104     cin.get();
    105 }
  • 相关阅读:
    洛谷3004 [USACO10DEC]宝箱Treasure Chest
    洛谷3778 [APIO2017]商旅
    洛谷4141消失之物——每个体积的角度
    洛谷2943 [USACO09MAR]清理Cleaning Up——转变枚举内容的dp
    bzoj1858[Scoi2010]序列操作
    poj1325机器工作——二分图最小点覆盖
    洛谷P1144——最短路计数
    poj3254二进制放牛——状态压缩DP
    poj1191棋盘分割——区间DP
    洛谷P1474货币系统——背包方案计数
  • 原文地址:https://www.cnblogs.com/xiaochi/p/8690691.html
Copyright © 2011-2022 走看看