2016-09-18 2 views
1

boost :: bind와 boost :: function을 사용하여 멤버 함수를 콜백으로 전달할 가능성을 조사했을 때 호기심에 걸렸습니다. 나는 두 클래스의 모델로 속고 있었다. 첫 번째 개체 (Organism)는 멤버 변수 (age)를 int (void) 함수 (getAge)를 통해 노출합니다. 두 번째 클래스 (생물 학자)는 boost :: 함수를 멤버 (callbackFunction)로 저장하고 학습 할 동물의 현재 나이 (takeNotes)를 사용하여 멤버 변수 m_notes의 나이를 유지합니다. 두 번째 클래스의 인스턴스 (steve_irwin)는 첫 번째 클래스의 인스턴스 (동물)를 '감시'(takeNotes)해야합니다.멤버 함수를 콜백, boost :: bind, boost :: function으로 전달하기

class Biologist { 
public: 
    void setCallback(boost::function<int(void)>); 
    void takeNotes(); 
    void tellAge(); 
private: 
    boost::function<int(void)> updateCallback; 
    int m_notes; 
}; 

void Biologist::setCallback(boost::function<int(void)> _f) { 
    updateCallback = _f; 
} 

void Biologist::takeNotes() { 
    m_notes = updateCallback(); 
} 

void Biologist::tellAge() { 
    std::cout << "The animal I am studying is : " << m_notes << 
     " years old! WOW!" << std::endl; 
} 

메인 루프는 다음과 같이 진행한다 : 이는 생물 클래스를 구현하는 코드 반면

class Organism { 
public: 
    Organism(int = 1); 
    void growOlder(); 
    int getAge(void); 
    void tellAge(void); 
private: 
    int m_age; 
}; 

Organism::Organism(int _age) : m_age(_age) {} 

void Organism::growOlder() { 
    m_age++; 
} 

int Organism::getAge(void) { 
    return m_age; 
} 

void Organism::tellAge(void) { 
    std::cout << "This animal is : " << m_age << " years old!"; 
} 

: 여기

코드 동물 클래스를 구현한다

Organism animal(3); 
Biologist steve_irwin; 

boost::function<int(void)> f = boost::bind(&Organism::getAge, animal); 
steve_irwin.setCallback(f); 

steve_irwin.takeNotes(); 
steve_irwin.tellAge(); 
animal.tellAge(); 

animal.growOlder(); 

steve_irwin.takeNotes(); 
steve_irwin.tellAge(); 
animal.tellAge(); 

나는 3 살짜리 동물을 만들고, 스티브 어윈에게 그것을 보라고 말한다. 처음에는 메모를 쓰고 ctly하지만, 동물이 더 자라서 나이를 다시 말한 후에, 그는 여전히 동물이 3 살이라고 생각합니다.

프로그램의 출력 : I는 I 든 참조하여 콜백 같은 멤버 함수 불합격 추측하고 있지만, I는 어디에 결정할 수

The animal I am studying is : 3 years old! WOW! 
This animal is : 3 years old! 
The animal I am studying is : 3 years old! WOW! 
This animal is : 4 years old! 

. 나 좀 도와 줄 수있어?

+0

무엇 boost documentation for boost::bind를 참조하십시오'부스트 : 심판 '(또는'표준 : ref' 당신의 C++ 버전에서 지원하는 경우)? –

답변

6

boost::function<int(void)> f = boost::bind(&Organism::getAge, animal); 대신 boost :: bind는 위와 같이 수행하면 개체의 내부 복사본을 만들기 때문에 boost::function<int(void)> f = boost::bind(&Organism::getAge, &animal);이어야합니다.

사용에 대한

관련 문제