C++ cocos2d-x can';t使用lambda更改变量的值

C++ cocos2d-x can';t使用lambda更改变量的值,c++,debugging,lambda,cocos2d-x,C++,Debugging,Lambda,Cocos2d X,我想用OnTouch方法捕捉触摸事件。我更喜欢使用lambda,因为它干净优雅 我的问题是: 在OnTouched中,打印的值不正确。为什么?这个价值是不合理的 我尝试将声明移动到GameSecene.h文件中。我甚至不会编译!请帮忙 // on "init" you need to initialize your instance bool GameScene::init() { ////////////////////////////// // 1. super init f

我想用OnTouch方法捕捉触摸事件。我更喜欢使用lambda,因为它干净优雅

我的问题是:

在OnTouched中,打印的值不正确。为什么?这个价值是不合理的

我尝试将声明移动到GameSecene.h文件中。我甚至不会编译!请帮忙

// on "init" you need to initialize your instance
bool GameScene::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }

    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

    auto backGroundSprite = Sprite::create("Background.jpg");
    backGroundSprite->setPosition( Point(visibleSize.width / 2 + origin.x,
                                         visibleSize.height / 2 + origin.y));
    this->addChild(backGroundSprite);


    int start_x, start_y, end_x, end_y;

    auto touchListener = EventListenerTouchOneByOne::create();
    touchListener->onTouchBegan = [&start_x, &start_y](Touch* touch, Event* event) -> bool {
        // your code
        auto touchPoint = touch->getLocation();
        start_x = touchPoint.x;
        start_y = touchPoint.y;
        return true;
    };

    touchListener->onTouchEnded = [start_x, start_y](Touch* touch, Event* event){
        // your code
        CCLOG("%d %d", start_x, start_y);
    };

    _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener,this);

    return true;
}

start_x
start_y
在函数退出时被销毁,因为它们是局部变量。非常感谢兄弟!我试图将declare移到.h文件中。但是我认为代码无法编译…您只显式地捕获了
ontouched
的变量值。如果你初始化它们,你会注意到你正在输出初始值。(当你通过引用捕获时,也存在无效引用的问题。)谢谢:)你能教我更多关于如何使其正确的知识吗?@shawn不是最复杂的软件工程解决方案,但它应该可以工作:使
start\u x
start\u y
成为
GameScene
的成员。通过引用捕获。并且总是初始化变量。
libpng warning: iCCP: known incorrect sRGB profile
2015-04-01 23:38:19.404 DR iOS[4206:72194] cocos2d: surface size: 2048x1536
2015-04-01 23:38:19.620 DR iOS[4206:72194] cocos2d: surface size: 2048x1536
32767 1382642256
32767 1382642256
32767 1382642256
32767 1382642256