C + + callback function

Source: Internet
Author: User

callback function, that is, we say that the implementation of the observer pattern, asynchronous programming, the key point in Java in general through anonymous class implementation is more, in C + +, unless the use of formal OO implementation, there are many use function pointers, especially in some cases may not allow the use of objects. Its basic usage is as follows.

Define related interfaces:

void Callbackfunc (char *);//function void Callbacker (char *,void (*fptr) (char *)) that defines the receive function pointer as a parameter, and typedef void (*callbacker) (cha r*);//defines the function that receives the function pointer as a parameter, alias way void Callbacker1 (char *,callbacker); Callbackfunc (char * str) {cout << str << Endl;} void Callbacker (char * str,void (*FPTR) (char *)) {(*fptr) (str);} void Callbacker1 (char * str,callbacker fptr) {(*fptr) (str);}

Call:

int_tmain (intARGC, _tchar*argv[]) {Vector<Char*>VF; Vf.push_back (" One"); Vf.push_back (" Both"); Vf.push_back ("three");intFi=0; void(*func) (Char*) =Callbackfunc; Callbacker Pfunc=Callbackfunc;  for(FI =0; Fi<vf.size (); fi++) {callbacker (vf[fi],func);    Callbacker1 (Vf[fi],pfunc); }}

The output is as follows:

One
One
Both
Both
Three
Three

Typically, a more common scenario is to pass an array of pointers to functions that are suitable for scenarios such as wind-control calculations, for different values or categories, and for different functions, so that you can achieve both polymorphism without the need to introduce the result of the class. Refer to the following:

http://blog.csdn.net/feitianxuxue/article/details/7300291

C + + callback function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.