在类定义中使用'this'

Use of 'this' within a class definition

本文关键字:this 定义      更新时间:2023-10-16

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

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

我不明白为什么绑定到 print 函数,因为 print 函数不接受任何参数(甚至没有错误代码)

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

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

有人可以启发我吗?

成员函数在对象上调用。这就是为什么有一个隐式this参数。如果没有类的有效实例,则不能调用成员函数。

出于这个原因,bind需要您传递调用成员的对象。

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