在类定义中使用'this'

Pie*_* P. 1 c++ boost-asio

在其中一个Boost.Asio教程中,他们在构造函数中调用计时器上的异步等待.

Printer(boost::asio::io_service& io) : timer_(io, boost::posix_time::seconds(1)), count_(0) {
    timer_.async_wait(boost::bind(&Printer::print, this));
}
Run Code Online (Sandbox Code Playgroud)

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么这个print函数绑定了函数,因为print函数不带任何参数(甚至不是错误代码)

在代码示例中,这是合理的.因为所有非静态类成员函数都具有隐式this参数,所以我们需要将其绑定到函数.

但我不明白需要绑定 的功能.

有人可以开导我这个吗?

Sto*_*ica 5

在对象上调用成员函数.这就是为什么有一个隐含的this参数.如果没有该类的有效实例,则无法调用成员函数.

bind 因此,需要您传递调用该​​成员的对象.