?? C + + Unlike many other programming languages have the concept of interface, delegation or protocol, but the use of pure virtual functions and C + + multiple inheritance, we can also implement interfaces, delegates or protocols to do things, the following through a person set the alarm clock and then wake up the alarm clock example to illustrate how to implement a delegate callback in C + +.
#include <iostream>#include <vector>#include <unistd.h>using STD::cout;using STD:: Endl;//Forward statementclassperson;//Implement a protocol with pure virtual function//The class that implements the protocol has a wake-up behaviorclassawakable { Public://Pure virtual function Virtual voidBeawaken () =0;};//Alarm classclassAlarmClock { Public://Principal (who commissioned the alarm to provide wake-up service)Awakable *delegate;//Alarm After a specified time voidAlarmafter (int)Const;};voidAlarmclock::alarmafter (intSecondsConst{Sleep (seconds);cout<<" Ding dong Ding Ding"<< Endl; Delegate->beawaken ();}//Human (implements the Awakable protocol can be awakened)classPerson: Publicawakable { Public://Start alarm and specify wake-up time voidRollclock (int);//The Awakened behavior in the Protocol voidBeawaken ();};voidPerson::rollclock (intseconds) {cout<<"People set the alarm."<< seconds <<"Bell after Seconds"<< Endl;//Create an Alarm object on the stackAlarmClock AC;//Set up the principal partyAc.delegate = This; Ac.alarmafter (seconds); }voidPerson::beawaken () {cout<<"People are awakened by the alarm clock."<< Endl;}intMainvoid) {//creator of the person's objectPerson *person =Newperson;//People start alarm set 5 seconds after wake upPerson->rollclock (5);return 0;}
?? The program is written here, and I believe that there is no more language to explain how to implement the protocol. In fact, the representation of various programming languages is ever-changing but virtually indistinguishable in substance. Similar functions can be done in Java with Interfaces (interface), with delegates (delegate) in C #, protocols (protocol) in Objective-c, and the concept of protocol in Swift. But if you can understand the concept of functional programming, there is a much simpler and more efficient way to use a lambda function to pass a callback function directly as a parameter into a function or method, while Java (Java 8) and C # provide a lambda expression. Blocks are also available in OC to achieve the same functionality. So what about C + +, and don't forget that there's also the concept of functor (function objects) in C + +, aren't they all consistent? Of course, the language that supports functional programming paradigms is not to mention, just as JavaScript can pass functions into functions, isn't swift?
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Example of implementing a protocol delegate with pure virtual function in C + +