lambda表达式

 1. 例子:代码来源

 1 #include <iostream>
 2 using namespace std;
 3 
 4 struct Foo
 5 {
 6   int x = 1;
 7 
 8   void foo(int x)
 9   {
10     auto f = [x, this] { cout << x << endl; };
11     f();
12   }
13 };
14 
15 int main()
16 {
17   Foo foo;
18   foo.foo(2); // 2
19 }

2. 例子

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class test
 5 {
 6 public:
 7   void hello()
 8   {
 9     cout << "test hello!n";
10   };
11   void lambda()
12   {
13     auto fun = [this] { // 捕获了 this 指针
14       this->hello();    // 这里 this 调用的就是 class test 的对象了
15     };
16     fun();
17   }
18 };
19 
20 int main()
21 {
22   test t;
23   t.lambda();
24 }