【问题标题】:Capturing member variable in C++ lambda function [duplicate]在C ++ lambda函数中捕获成员变量[重复]
【发布时间】:2019-09-13 04:23:01
【问题描述】:
class A{
public:
    void do_something(std::function<void()> const& f) {

    }
};

class B: public A{
public:
    int x = 0;
    void do_another_thing(){
     do_something([x]{});   
    }
};

它说 x 不是一个变量:

16:20: error: capture of non-variable 'B::x' 
14:13: note: 'int B::x' declared here

为什么它不能与类成员一起使用,但它可以与定义在 do_another_thing() 中的变量一起使用?

【问题讨论】:

标签: c++


【解决方案1】:

void do_another_thing() {
do_something([x]{});
}

问题在于 x 不是 lambda 定义的直接范围内的变量。因此无法捕获。同意 x 是在函数上方声明的类成员,但这不会使其对 lambda 可见。您可以改为捕获 this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    相关资源
    最近更新 更多