|
楼主 |
发表于 2015-9-18 21:21:57
|
显示全部楼层
转角 发表于 2015-9-16 20:58
这真不是回调。说它是个重写还不是重写,根本就是两个类里面互相包含了个对象而已。
- //
- // main.cpp
- // Lambda
- //
- // Created by Atropos on 15/9/2.
- // Copyright © 2015年 Atropos. All rights reserved.
- //
- #include <iostream>
- #include <string>
- #include "ClassTemplate.hpp"
- #include <pthread.h>
- #include <unistd.h>
- // 串口的事件处理接口
- class Event_receive {
- public:
- Event_receive() {}
-
- virtual int event(std::string str) = 0;
- };
- // 串口类定时一秒发一次;
- class USART_EXAMPLE {
- public:
- USART_EXAMPLE(Event_receive *ptr)
- : _usr(ptr)
- {
- pthread_create(&_pthread, NULL, task, this);
- }
-
- ~USART_EXAMPLE() {
- pthread_join(_pthread, NULL);
- }
-
- private:
- // 使用者的指针用于回调接口
- Event_receive *_usr;
-
- // 线程号
- pthread_t _pthread;
-
- private:
- // c调用c++的转换接口
- static void * task (void * ptr) {
- USART_EXAMPLE *func = (USART_EXAMPLE *)ptr;
-
- func->taskHandle();
- return 0;
- }
- // 定时发送
- void taskHandle() {
- while (true) {
- sleep(1);
- _usr->event("123");
- }
- }
- };
- class Usr
- // 实现事件接口
- : public Event_receive
- {
- public:
- Usr() : _usart(this) {}
- private:
- // 实例化一个串口
- USART_EXAMPLE _usart;
-
- private:
- // 事件处理函数供串口接收调用
- virtual int event(std::string str) {
- std::cout << str << std::endl;
- return 1;
- }
- };
- int main(int argc, const char * argv[]) {
-
- Usr usr;
- return 0;
- }
复制代码 |
|