c++ lambda表达式捕获类数据…

来源:互联网 发布:华三交换机端口配置 编辑:程序博客网 时间:2024/06/05 20:33

lambda表达式允许捕获局部变量,但是数据成员不是局部变量。用一种特殊的方法,你可以捕获“this”:。

using namespace std;

class Kitty {
public:
    explicitKitty(int toys) : m_toys(toys) { }

    voidmeow(const vector& v) const {
       for_each(v.begin(), v.end(), [this](int n){
           cout << "If you gave me " << n << " toys, I wouldhave " << n + m_toys << " toys total." <<endl;
       }
);
    }

private:
    intm_toys;
};

int main() {
    vectorv;

    for (int i =0; i < 3; ++i) {
       v.push_back(i);
    }

    Kittyk(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:
    explicitKitty(int toys) : m_toys(toys) { }

    voidmeow(const vector& v) const {
       for_each(v.begin(), v.end(), [=](int n){
           cout << "If you gave me " << n << " toys, I wouldhave " << n + m_toys << " toys total." <<endl;
       }
);
    }

private:
    intm_toys;
};

int main() {
    vectorv;

    for (int i =0; i < 3; ++i) {
       v.push_back(i);
    }

    Kittyk(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 遇到了问题,查了查,然后记下来了

0 0
原创粉丝点击