“[这个]"是什么意思?C++中的意思 [英] What does "[ this ]" mean in C++

查看:53
本文介绍了“[这个]"是什么意思?C++中的意思的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我阅读 Cocos2dx 3.0 API 时,我发现了这样的东西:

When I was reading the Cocos2dx 3.0 API, I found something like this:

auto listener = [this](Event* event){
    auto keyboardEvent = static_cast<EventKeyboard*>(event);
    if (keyboardEvent->_isPressed)
    {
        if (onKeyPressed != nullptr)
            onKeyPressed(keyboardEvent->_keyCode, event);
    }
    else
    {
        if (onKeyReleased != nullptr)
            onKeyReleased(keyboardEvent->_keyCode, event);
    }
};

[this] 是什么意思?这是 C++11 中的新语法吗?

What does [this] mean? Is this new syntax in C++11?

推荐答案

[this] 是什么意思?

What does [this] means?

它引入了一个 lambda - 一个可调用的函数对象.将 this 放在括号中意味着 lambda 捕获 this,因此该对象的成员在其中可用.Lambda 还可以通过值或引用捕获局部变量,如链接页面中所述.

It introduces a lambda - a callable function object. Putting this in the brackets means that the lambda captures this, so that members of this object are available within it. Lambdas can also capture local variables, by value or reference, as described in the linked page.

lambda 有一个 operator() 的重载,所以它可以像函数一样被调用:

The lambda has an overload of operator(), so that it can be called like a function:

Event * event = some_event();
listener(event);

它将运行在 lambda 的主体中定义的代码.

which will run the code defined in the body of the lambda.

这是 C++11 中的新语法吗?

Is this new syntax in C++11?

是的.

这篇关于“[这个]"是什么意思?C++中的意思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆