//==== 1 ====
string func1(string x1, string x2){
return x1 + x2;
}
auto lambda1 = [](string x1, string x2){cout << func1(x1,x2);};
//==== 2 ====
class Test{
public:
string func2(string x1, string x2){
return x1 + x2;
}
void tst(){
auto lambda2 = [](string x1, string x2){cout << func2(x1,x2);};
}
};
lambda1 是对的。 但是 lambda2 出现错误(在 g++ 4.8 下):
error: 'this' was not captured for this lambda function
auto lambda2 = [](string x1, string x2){cout << func2(x1,x2);};
在 lambda 中调用成员函数的正确方法是什么?
最佳答案
编译器给你你正在寻找的答案:
error: 'this' was not captured for this lambda function
您需要在 []
括号内提供一个 this
捕获:
auto lambda2 = [this](string x1, string x2){cout << func2(x1,x2);};
没有它,编译器将不知道变量的上下文。请注意,x1
和 x2
都将被复制。
阅读更多关于 lambda 捕获的信息 here .
关于c++ - 无法在 C++ lambda 表达式中调用类成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32774451/