当使用这种在拉姆达类功能

问题描述 投票:1回答:1

当应this在拉姆达被用来调用类的成员函数?我有一个例子所示,其中hello();被称为无thisthis->goodbye();的作用:

#include <iostream>

class A
{   
    void hello() { std::cout << "hello" << std::endl; }
    void goodbye() { std::cout << "goodbye" << std::endl; }

public:  
    void greet()
    {   
        auto hi = [this] () { hello(); }; // Don't need this.
        auto bye = [this] () { this->goodbye(); }; // Using this.

        hi();
        bye();
    }   
};  


int main()
{   
    A a;
    a.greet();
    return 0;
}   

是否有任何优势,比其他的一种方式?

编辑:对于hello拉姆达没有捕获任何,但它继承了存在于类范围的功能。它不能为会员做到这一点,为什么它的功能做到这一点?

c++ lambda this
1个回答
2
投票

this更加明确和更详细。

但它可能还需要与隐藏成员(捕获或参数)变量:

auto goodbye = [](){}; // Hide method
auto bye = [=] (int hello) {
    this->goodbye(); // call method
    goodbye(); // call above lambda.
    this->hello(); // call method
    std::cout << 2 * hello; // show int parameter.
};
© www.soinside.com 2019 - 2024. All rights reserved.