繁体   English   中英

将成员函数作为回调传递,boost :: bind,boost :: function

[英]Passing a member function as a callback, boost::bind, boost::function

当研究使用boost :: bind和boost :: function将成员函数作为回调传递的可能性时,我偶然发现了一个好奇心。 我当时在愚弄两个班级的模型。 第一个(有机体)通过int(void)函数(getAge)公开其成员变量(age)。 第二类(生物学家)将boost :: function作为成员存储(callbackFunction),并使用它确定(takeNotes)正在研究的动物的当前年龄(将年龄保留在成员变量m_notes中)。 第二类的实例(steve_irwin)应该“监视”(takeNotes)第一类的实例(动物)。

这是实现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!";
}

而这是实现Biologist类的代码:

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岁的动物,我告诉史蒂夫·欧文(Steve Irwin)观察它,他首先记下便正确地告诉了它的年龄,但是在动物长大之后又再次告诉它的年龄,他仍然认为动物是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!

我猜我无法通过引用将成员函数作为回调传递,但我无法确定在哪里。 你能帮助我吗?

代替boost::function<int(void)> f = boost::bind(&Organism::getAge, animal); 应该是boost::function<int(void)> f = boost::bind(&Organism::getAge, &animal); ,因为如果执行上述操作,则boost :: bind会创建对象的内部副本。

请参阅Boost文档以获取boost :: bind

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM