目录
数字货币
云计算
编程
网络
其他
架构设计
密码学
boost信号槽编程
signal-slot是一个非常方便的接口机制,在boost库中同样也实现了signal-slot,下面我体验下: 1
button.h头文件:
//button.h
#ifndef __EXAM_H__
#define __EXAM_H__
#include <boost/signal.hpp>
#include <boost/bind.hpp>
class Button
{
typedef boost::signal<void (int x, int y)> OnClick;
public:
Button(){};
void init();
void print(long x, long y);
void notify(long x, long y);
void show(long x, long y);
void press(int x, int y) {
onClick(x, y);
}
private:
OnClick onClick;
};
#endif //__EXAM_H__
button.cpp源文件:
//button.cpp
#include <iostream>
#include "button.h"
void Button::init()
{
onClick.connect(boost::bind(&Button::print, this, _1, _2));
onClick.connect(boost::bind(&Button::notify, this, _1, _2));
onClick.connect(boost::bind(&Button::show, this, _1, _2));
}
void Button::print(long x, long y)
{
std::cout<<"Print Clicked @(" << x << "," << y <<")\n";
}
void Button::notify(long x, long y)
{
std::cout<<"Notify Clicked @(" << x << "," << y <<")\n";
}
void Button::show(long x, long y)
{
std::cout<<"Show Clicked @(" << x << "," << y <<")\n";
}
main.cpp源文件
//main.cpp
#include <iostream>
#include <boost/bind.hpp>
//#include <boost/function>
#include "button.h"
void button_click_test()
{
Button button;
button.init();
std::cout<<"===== button onclick test\n";
button.press(200,300);
button.press(20,30);
button.press(19,3);
}
int main(int argc, char *argv[])
{
button_click_test();
return 0;
}
Makefile文件:
#Makefile
OBJS = button.o main.o
CC = g++
LIBS = -l boost_signals
CFLAGS = -Wall -O -g
myprog : $(OBJS)
$(CC) $^ -o $@ $(LIBS)
main.o : main.cpp
$(CC) $(CFLAGS) -c $< -o $@ $(LIBS)
button.o : button.cpp button.h
$(CC) $(CFLAGS) -c $< -o $@ $(LIBS)
.PYONY: clean
clean:
rm -rf $(OBJS)
rm -rf myprog
编译并执行:
# make
g++ -Wall -O -g -c button.cpp -o button.o -l boost_signals
g++ button.o main.o -o myprog -l boost_signals
# ./myprog
===== button onclick test
Print Clicked @(200,300)
Notify Clicked @(200,300)
Show Clicked @(200,300)
Print Clicked @(20,30)
Notify Clicked @(20,30)
Show Clicked @(20,30)
Print Clicked @(19,3)
Notify Clicked @(19,3)
Show Clicked @(19,3)