c++lambda表达式作为函数参数引用this会报错
在 lambda 表达式中引用 this 指针时,需要注意 lambda 表达式的捕捉列表。如果没有将 this 指针捕捉到 lambda 表达式中,就无法在 lambda 表达式中使用 this 指针。此外,还需要注意 lambda 表达式的使用方式,如果使用方式不正确,也可能导致错误。
以下是一个示例代码,演示了如何在 lambda 表达式中引用 this 指针:
class MyClass {
public:
void foo() {
int a = 10;
auto func = [this, &a]() {
// 在 lambda 表达式中使用 this 指针和局部变量 a
std::cout << "this->x = " << x << std::endl;
std::cout << "a = " << a << std::endl;
};
func();
}
private:
int x = 0;
};
int main() {
MyClass obj;
obj.foo();
return 0;
}
在上面的示例代码中,我们在 lambda 表达式中捕捉了 this 指针和局部变量 a。然后我们定义了一个函数 func,将 lambda 表达式赋值给它,并在函数内部调用该函数。
当我们调用 obj.foo() 时,会输出以下内容:
this->x = 0
a = 10
这表明我们成功地在 lambda 表达式中使用了 this 指针和局部变量 a。
如果没有将 this 指针捕捉到 lambda 表达式中,就无法在 lambda 表达式中使用 this 指针。例如,以下代码会编译错误:
class MyClass {
public:
void foo() {
auto func = []() {
// 在 lambda 表达式中使用 this 指针会报错
std::cout << "this->x = " << x << std::endl;
};
func();
}
private:
int x = 0;
};
int main() {
MyClass obj;
obj.foo();
return 0;
}
在上面的示例代码中,我们没有将 this 指针捕捉到 lambda 表达式中,因此在 lambda 表达式中使用 this 指针会编译错误
原文地址: https://www.cveoy.top/t/topic/fIuT 著作权归作者所有。请勿转载和采集!