플밍

c++에서 Delegate(콜백함수) 구현 본문

프로그래밍/C/C++

c++에서 Delegate(콜백함수) 구현

너구리안주 2014. 3. 25. 14:17

그동안 c++ 에서 콜백함수를 구현하는걸 상당히 어렵해 해왔었다.

객체와 메서드를 주고 typedef 만들고 괄호에 신경쓰고... 암튼 할때마다 형식이 안외어져서 힘들었는데

생각외로 간단히 해결이 된다.

그냥 java나 c#처럼 사용하면 되는걸 모르고 이 고생을 했다니 ㅜㅜ

#ads_1

아래는 예제


#include <iostream>

using namespace std;

class Animal;

class AnimalDelegate{
public:
    virtual void onSound(Animal* pSender)=0;
    virtual void onWalk(Animal* pSender)=0;
};

class Animal{
private:
    AnimalDelegate* delegate;

public:

    Animal(){
        this->delegate = NULL;
    }

    void setDelegate(AnimalDelegate* delegate){
        this->delegate = delegate;
    }

    void sound(){
        if(this->delegate){
            this->delegate->onSound(this);
        }
    }

    void walk(){
        if(this->delegate){
            this->delegate->onWalk(this);
        }
    }
};



//개 : Delegate를 내부에 직접 구현
class Dog:public Animal, public AnimalDelegate{
public:
    Dog(){
        this->setDelegate(this);
    }

    void onSound(Animal* pSender){
        cout << "Dog: 멍멍!" << endl;
    }

    void onWalk(Animal* pSender){
        cout << "Dog: 개가 걷는다" << endl;
    }
};

//고양이 Delegate
class CatDelegate:public AnimalDelegate{
public:
    void onSound(Animal* pSender){
        cout << "Cat: 야옹~" << endl;
    }

    void onWalk(Animal* pSender){
        cout << "Cat: 고양이가 걷는다" << endl;
    }
};

//고양이
class Cat:public Animal{};


void main(){

    Dog dog;
    Cat cat;

    dog.sound();
    dog.walk();
   
    CatDelegate cdel;

    cat.setDelegate(&cdel);
    cat.sound();
    cat.walk();
   
    getchar();
}

#ads_2

Comments