2016-09-18 11 views
1

boost :: bindとboost :: functionを使ってメンバー関数をコールバックとして渡す可能性を調べるとき、私は好奇心に遭遇しました。私は2つのクラスのモデルでうろついていました。最初のもの(Organism)はメンバ変数(age)をint(void)関数(getAge)で公開します。 2番目のクラス(Biologist)はboost ::関数をメンバ(callbackFunction)として保存し、学習中の動物の現在の年齢(メンバ変数m_notesの年齢を保持する)を決定するためにtakeNotesを使用します。第2クラスのインスタンス(steve_irwin)は、第1クラスのインスタンス(動物)を「監視」(takeNotes)することになっています。ここでメンバー関数をコールバックboost :: bindとboost :: functionとして渡す

は、Animalクラスを実装するコードです:

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!"; 
} 

これは生物学者のクラスを実装するコードであるのに対し:

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; 
} 

メインループはこのように書き:

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歳だと考えています。

プログラムの出力:

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

何を参照してください? –

答えて

6

boost::function<int(void)> f = boost::bind(&Organism::getAge, animal);の代わりに、boost::function<int(void)> f = boost::bind(&Organism::getAge, &animal);にする必要があります。これは、上記のようにboost :: bindがオブジェクトの内部コピーを作成するためです。

は、 '(あなたのC++バージョンがサポートしている場合はstd :: ref` `REF ::ブーストまたは')の使用についてboost documentation for boost::bind

関連する問題