在 class 定义中使用 'this'

Use of 'this' within a class definition

在其中一个 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 绑定到 print 函数,因为 print 函数不带任何参数(甚至连错误代码)

在代码示例中,这是合理的 因为所有非静态 class 成员函数都有一个隐含的 this 参数,我们需要将 this 绑定到函数。

但我不明白 需要this 绑定到函数。

有人可以启发我吗?

在对象上调用了成员函数。这就是为什么有一个隐含的 this 参数。如果没有 class.

的有效实例,则不能调用成员函数 出于这个原因,

bind 需要您传递调用成员的对象。

print函数是classPrinter的非静态成员函数。就像所有其他非静态成员函数一样,它接收一个隐式 this 参数,允许它访问 class 实例字段(在本例中为 timer_count_)。可以通过提升时间调用的函子被限制为没有参数,这就是 bind 提供救援的地方,提供 operator () 由计时器调用,然后在内部调用 Printer::print存储 this 指针。