深入浅出 C++ Lambda表达式:语法、特点和应用

深入浅出 C++ Lambda表达式:语法、特点和应用

以上链接有错误的地方:

auto f = [*this] () { return num + x; };
// 应改为:
auto f = [*this, x] () { return num + x; };

若改成以下

auto f = [x] () { return num + x; };

在C++ Shell中有如下编译错误
main.cpp:16:34: error: ‘this’ cannot be implicitly captured in this context
auto f = [x] () { return num + x; };
^
main.cpp:16:20: note: explicitly capture ‘this’
auto f = [x] () { return num + x; };
^
, this
1 error generated.

auto f = [this, x] () { return num + x; };auto f = [*this, x] () { return num + x; };
一样能编译通过和一样的结果
#include 
using namespace std;

// 定义一个类
class Test
{
public:
    Test(int n) : num(n) {} // 构造函数,初始化 num
    void show() // 成员函数,显示 num
    {
        cout << num << endl;
    }
    void add(int x) // 成员函数,增加 num
    {
        // 定义一个 Lambda表达式,捕获 this 指针
        auto f = [*this, x] () { return num + x; };
        // 调用 Lambda表达式
        cout << f() << endl;
    }
private:
    int num; // 成员变量,存储一个整数
};

int main()
{
    Test t(10); // 创建一个 Test 对象
    t.show(); // 调用成员函数,输出 10
    t.add(5); // 调用成员函数,输出 15

    return 0;
}

你可能感兴趣的:(c++)