c++ - 在类定义中使用 'this'

标签 c++ boost-asio

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/

相关文章:

c++ - 停止 boost::asio 操作的规范方法

c++ - 从 GUI 在 Excel 中打开指定文件 - Borland C++

c++ - 带有大括号初始化的 make_unique

c++ - 带有 C++11 lambda 的 C 函数指针

c++ - Boost::Asio,SSL 连接问题

c++ - Boost::Thread - 线程创建问题

c++ - QSqlTableModel::setData() 对于 Qt::EditMode 也返回 false

c++ - 同时调用 ASIO 对象的 API 是否安全?

c++ - 如何指定要在用 C++ 编写的应用程序中使用的特定 NIC (boost asio)

c++ - 奇怪的 C4512 警告。为什么?