C + + virtual functions and function pointers are used together

Source: Internet
Author: User

C + + virtual functions and function pointers are used together, which is a bit cumbersome to write.

A sample code is posted below for reference. (Need to support C++11 compilation)

1#include <stdio.h>2#include <list>3 using namespacestd;4 5 classVirtualwithcallback {6  Public:7     usingCallBack =void(Virtualwithcallback::*) (int);8 9  Public:Ten     Virtual voidTestcallback (intARG) =0; One  A     VirtualCallBack Getcallback ()Const=0; - }; -  the classVirtualWithCallBackSample1: PublicVirtualwithcallback { -  Public: - VirtualWithCallBackSample1 () { -CallBack = &Virtualwithcallback::testcallback; +     } -  +  Public: A     voidTestcallback (intArgOverride { atprintf"This is the virtual call 1:arg =%d\n", ARG); -     } -  -CallBack Getcallback ()Const Override { -         returnCallBack; -     } in  - Private: toCallBack CallBack =nullptr; + }; -  the classVirtualWithCallBackSample2: PublicVirtualwithcallback { *  Public: $ VirtualWithCallBackSample2 () {Panax NotoginsengCallBack = &Virtualwithcallback::testcallback; -     } the  +  Public: A     voidTestcallback (intArgOverride { theprintf"This is the virtual call 2:arg =%d\n", ARG); +     } -  $CallBack Getcallback ()Const Override { $         returnCallBack; -     } -  the Private: -CallBack CallBack =nullptr;Wuyi }; the  - classVirtualcaller { Wu  Public: -     voidPush (virtualwithcallback*callBack) { About Callbacklist.push_back (callBack); $     } -  -     voidrun () { -          for(Auto r:callbacklist) { A(R->* (R->getcallback ())) ( About); +         } the     } -  $ Private: theList<virtualwithcallback*>callbacklist; the }; the  the intMain () { - Virtualcaller caller; inCaller.push (NewVirtualWithCallBackSample1 ()); theCaller.push (NewVirtualWithCallBackSample2 ()); the Caller.run (); About     return 0; the}

Run results

This article by Hassan Ya Qi Original, reproduced please indicate the source.

C + + virtual functions and function pointers are used together

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.