ITPub博客

首页 > IT职业 > IT职场 > boost的signal和solt机制使用入门

boost的signal和solt机制使用入门

IT职场 作者:xu_xufei 时间:2021-09-09 09:14:47 0 删除 编辑
boost的signal和solt机制使用入门


signal-slot是一个非常方便的接口机制,在Qt和Gtk中广泛使用。boost也实现了一个signal-slot机制。


view plain copy
  1. void printCoordinates(long x, long y)  

  2. {  

  3.     std::cout

  4. }  

  5.   

  6. void button_click_test()  

  7. {  

  8.     Button button;  

  9.   

  10.     button.addOnClick(&printCoordinates);  

  11.   

  12.     std::cout

  13.   

  14.     button.press(200,300);  

  15.     button.press(20,30);  

  16.     button.press(19,3);  

  17. }  

button.addOnClick可以直接接收任何能够被signal.connect接受的参数。

view plain copy
  1. class TextView : public View  

  2. {  

  3. public:  

  4.     TextView(Document& doc) : View(doc) { }  

  5.   

  6.     virtual void refresh(bool bExtended) const {  

  7.         std::cout 

  8.     }  

  9. };  

  10.   

  11. class HexView : public View  

  12. {  

  13. public:  

  14.     HexView(Document& doc) : View(doc) { }  

  15.   

  16.     virtual void refresh(bool bExtended) const {  

  17.         std::cout 

  18.         const std::string& s = m_doc.getText();  

  19.   

  20.         for(std::string::const_iterator it = s.begin();  

  21.             it != s.end(); ++it)  

  22.             std::cout (*it);  

  23.         std::cout 

  24.     }  

  25. };  


使用方法:

  1. void document_view_test()  

  2. {  

  3.     Document doc;  

  4.     TextView v1(doc);  

  5.     HexView  v2(doc);  

  6.   

  7.     std::cout

  8.   

  9.     doc.append("Hello world!n");  

  10.     doc.append("Good!n");  

  11.     doc.append("Happy!n");  

  12. }  


该代码运行后,可以看到如下的结果

  1. ================= document view test ===============  

  2. TextView:Hello world!  

  3.   

  4. HexView:  48 65 6c 6c 6f 20 77 6f 72 6c 64 21 a  

  5. TextView:Hello world!  

  6. Good!  

  7.   

  8. HexView:  48 65 6c 6c 6f 20 77 6f 72 6c 64 21 a 47 6f 6f 64 21 a  

  9. TextView:Hello world!  

  10. Good!  

  11. Happy!  

  12.   

  13. HexView:  48 65 6c 6c 6f 20 77 6f 72 6c 64 21 a 47 6f 6f 64 21 a 48 61 70 70 79 21 a 

原文出处

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4684/viewspace-2801116/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-30

  • 博文量
    94
  • 访问量
    852