&是什么QUOT; [这里]"意味着C ++ [英] What does "[ this ]" mean in C++

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

问题描述

当我读 Cocos2dx 3.0 API,我发现这样的事情:

 自动监听= [这](事件*事件){
    汽车的KeyboardEvent =的static_cast< EventKeyboard *>(事件);
    如果(keyboardEvent-> _is pressed)
    {
        如果(安其pressed!= nullptr)
            安其pressed(keyboardEvent-> _key code,事件);
    }
    其他
    {
        如果(onKeyReleased!= nullptr)
            onKeyReleased(keyboardEvent-> _key code,事件);
    }
};

这是什么 [这] 是什么意思?在 C ++ 11

这种新语法
解决方案

  

这是什么[这]意味着什么?


它引入了一个拉姆达 - 一个可调用的函数对象。把这个括号意味着拉姆达的捕获这个,使这一成员对象是内部可用。 lambda表达式也可以捕获局部变量,由值或参考,如在链接的页面描述

该拉姆达具有过载操作符(),以便它可以被称为像函数:

 事件*事件= some_event();
监听器(事件);

这将运行在拉姆达的身体定义的code。


  

在C ++ 11?

这种新语法

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);
    }
};

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

解决方案

What does [this] means?

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.

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

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

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

Is this new syntax in C++11?

Yes.

这篇关于&是什么QUOT; [这里]&QUOT;意味着C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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