將類的成員函數註冊為回呼函數

來源:互聯網
上載者: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);(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 /*即便是傳遞的pA指標任然可以調用B的成員函數,類似將A* 強制轉換為了 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
請按任意鍵繼續. . .

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.