Register a class member function as a callback function

Source: Internet
Author: User
# Include <iostream> Class Object {}; typedef int (Object: * sayfunc) (const char *); Class A: Public object {public: int say (const char * MSG) {STD: cout <"A say" <MSG <STD: Endl; return 0 ;}; Class B: public object {public: int run (const char * MSG) {STD: cout <"B run" <name <MSG <STD: Endl; return 0;} Char name [64] ;}; class controller {public: controller (sayfunc fun, object * Target) {This-> fun = fun; This-> Target = target ;}~ Controller () {} void dofun (const char * MSG) {// (Target-> * Fun) (MSG );} PRIVATE: sayfunc fun; object * target;}; int main (void) {A * pA = new A; Controller * pcontroller1 = new controller (sayfunc) & A: Say, pa); pcontroller1-> dofun ("XXX1"); Controller * pcontroller2 = new controller (sayfunc) & B: Run, PA/* even if the passed PA pointer can call the member function of B, it is similar to forcibly converting a * to B **/); pcontroller2-> dofun ("xxx2 "); B * pb = new B; strcpy (Pb-> name, "Vicky"); Controller * pcontroller3 = new controller (sayfunc) & B: Run, Pb ); pcontroller3-> dofun ("xxx3"); System ("pause"); Return 0 ;}

 

A say XXX1
B run xxx2
B run vickyxxx3
Press any key to continue...

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.