在 Boost.Asio tutorial 之一中,他们在构造函数中调用异步等待计时器。
Printer(boost::asio::io_service& io) : timer_(io, boost::posix_time::seconds(1)), count_(0) {
timer_.async_wait(boost::bind(&Printer::print, this));
}
print
是
void print()
{
if (count_ < 5)
{
std::cout << count_ << std::endl;
++count_;
timer_.expires_at(timer_.expires_at() + boost::posix_time::seconds(1));
timer_.async_wait(boost::bind(&printer::print, this));
}
}
我不明白为什么 this 绑定(bind)到 print
函数,因为 print
函数不接受任何参数(甚至错误代码)
在代码示例中,这是合理的因为所有非静态类成员函数都有一个隐式的 this 参数,我们需要将 this 绑定(bind)到函数。
但我不明白需要将this绑定(bind)到函数。
有人可以启发我吗?
最佳答案
成员函数在对象上被调用。这就是为什么有一个隐式的 this
参数。如果没有类的有效实例,则不能调用成员函数。
bind
需要您传递调用成员的对象。
关于c++ - 在类定义中使用 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47159240/