【问题标题】:How to change a string variable inside a lambda expression?如何更改 lambda 表达式中的字符串变量?
【发布时间】:2020-11-12 05:07:57
【问题描述】:

我在 cocos2dx 中工作,我试图在 lambda 表达式中更改一个名为 selectedBlockTexture 的字符串变量的值,该表达式充当按钮按下的回调。不幸的是,我找不到解决这个问题的方法,它一直告诉我在特定的内存位置有未处理的异常。

变量 selectedBlockTexture 是在这个 for 循环之外声明的,并且循环会遍历字典以自动生成按钮,这些按钮可以让我更改 selectedBlockTexture 变量的值。

for (auto it : blockDict) {
    auto newBlockButton = Button::create("button-block-basic.png", "button-block-basic.png", button-block-basic.png");
    auto buttonImage = Sprite::create(it.first);

    newBlockButton->setPosition(Vec2(76 * blockDictIter, 64));
    buttonImage->setPosition(Vec2(76 * blockDictIter, 64));
    buttonImage->setGlobalZOrder(2);
    buttonImage->setScale(0.75);

    newBlockButton->addTouchEventListener([&](Ref* sender, Widget::TouchEventType type) {
        switch (type)
        {
        case ui::Widget::TouchEventType::BEGAN:
            break;
        case ui::Widget::TouchEventType::ENDED:
            chosenBlockTexture = it.first
            break;
        default:
            break;
        }
     });

    blockDictIter++;

    newBlockButton->setGlobalZOrder(1);
    this->addChild(newBlockButton);
    this->addChild(buttonImage);
}

This is the error I keep getting

【问题讨论】:

    标签: cocos2d-x


    【解决方案1】:

    如果变量 selectedBlockTexture 是方法变量,编译器将找不到错误:

    std::string chosenBlockTexture = "123";
    Button* playButton = Button::create("butplay.png",
                                       "butplay_in.png"
                                        );
    playButton->setPosition(Vec2(58.0f, 32.0f));
    playButton->addTouchEventListener([&](Ref* sender, Widget::TouchEventType type) {
        switch (type)
        {
        case ui::Widget::TouchEventType::BEGAN:
            break;
        case ui::Widget::TouchEventType::ENDED:
                chosenBlockTexture = "pipo";
                CCLOG("chosenBlockTexture = %s", chosenBlockTexture.c_str());
            break;
        default:
            break;
        }
     });
    

    输出是: selectedBlockTexture = ~\336

    上面的例子可以编译,但是 CCLOG 没有给出结果字符串“pipo”。

    当按下按钮时,var 超出范围,它会给出意想不到的结果(我使用 xcode iOS)。

    如果我将 selectedBlockTexture 设为私有变量(将变量设为私有 var,并将其从方法中删除),它的工作正常且输出为“chosenBlockTexture = pipo”。

     private:
        std::string chosenBlockTexture = "123";
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-24
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多