在类定义中使用'this'
Use of 'this' within a class definition
在 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
的地方。
相关文章:
- 在提升multi_index容器中,是否定义了"default index"?
- 表示"accepting anything for this template argument" C++概念的通配符
- #定义c-预处理器常量..我做错了什么
- 为什么使用 "this" 指针调用派生成员函数?
- 在 c++ 中正确定义"this"关键字?
- 是否是从等待返回到悬而未决的"this"实例的未定义行为?
- 定义非静态成员时获取C++中的"this"类型
- 如何设置"this"线程的自定义名称?
- 为什么 gcc 7.3 接受静态定义中的'this'?
- C++自定义迭代器和(*this)
- 指针上的const_cast "this"是未定义的行为吗?
- 通过"this"访问另一个对象的定义?
- 在构造函数中使用关键字 "this" 时定义复制构造函数
- 在类定义中使用'this'
- 方法定义中的错误"passing const List<int> as this argument discards qualifiers"
- 由 sf::P acket 定义的运算符<<是否与 sf::P acket 派生类的 (*this) 一起工作?
- 是否应该延迟类模板定义中由 this-> 限定的类/命名空间名称的名称查找?
- "Was not declared in this scope"错误结构定义。C++
- 大小(*this)在类定义中
- 从"this"中抛弃恒常性,然后更改成员值是否会调用未定义的行为?