概述
lambda表达式允许捕获局部变量,但是数据成员不是局部变量。用一种特殊的方法,你可以捕获“this”:。
using namespace std;
class Kitty {
public:
explicit Kitty(int toys) : m_toys(toys) { }
void meow(const vector& v) const {
for_each(v.begin(), v.end(), [this](int n) {
cout << "If you gave me " << n << " toys, I would have " << n + m_toys << " toys total." << endl;
});
}
private:
int m_toys;
};
int main() {
vector v;
for (int i = 0; i < 3; ++i) {
v.push_back(i);
}
Kitty k(5);
k.meow(v);
}
If you gave me 0 toys, I would have 5 toys total.
If you gave me 1 toys, I would have 6 toys total.
If you gave me 2 toys, I would have 7 toys total.
当你捕获了this以后,m_toys就可以使用了,它隐式的表示this->m_toys,你也可以显示的说明this->m_toys。(在lambda表达式中,只有捕获了this后才可以使用它,你永远无法得到lambda表达式本身的this指针)
你也可以隐式的捕获this:
using namespace std;
class Kitty {
public:
explicit Kitty(int toys) : m_toys(toys) { }
void meow(const vector& v) const {
for_each(v.begin(), v.end(), [=](int n) {
cout << "If you gave me " << n << " toys, I would have " << n + m_toys << " toys total." << endl;
});
}
private:
int m_toys;
};
int main() {
vector v;
for (int i = 0; i < 3; ++i) {
v.push_back(i);
}
Kitty k(5);
k.meow(v);
}
C:Temp>cl /EHsc /nologo /W4 implicitmemberkitty.cpp > NUL && implicitmemberkitty
If you gave me 0 toys, I would have 5 toys total.
If you gave me 1 toys, I would have 6 toys total.
If you gave me 2 toys, I would have 7 toys total.
你也可以使用“[&]”,但是它不会影响this的捕获方式(永远按值传递)。“[&this]”是不允许的。
上面代码不是自己的,今天做到c++ primer(第五版) 13.43 遇到了问题,查了查,然后记下来了
最后
以上就是害怕小猫咪为你收集整理的c++ lambda表达式捕获类数据…的全部内容,希望文章能够帮你解决c++ lambda表达式捕获类数据…所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复