【问题标题】:What does range-for loop exactly do?range-for 循环究竟做了什么?
【发布时间】:2017-08-11 16:36:05
【问题描述】:

我正在开发一个蛇游戏程序。我在 Snake 类中使用 Body 的双端队列来表示蛇,当然 Body 是我定义的结构。以下是部分代码:

struct Body {        // one part of snake body
    int x, y, direction;
    Body() : x(0), y(0), direction(UP) { }
    Body(int ix, int iy, int id) : x(ix), y(iy), direction(id) { }
};

class Snake {
protected:
    std::deque<Body> body;
    // other members
public:
    auto begin()->std::deque<Body>::const_iterator const { return body.cbegin(); }
    auto end()->std::deque<Body>::const_iterator const { return body.cend(); }
    // other members
};

在另一个函数construct_random_food 中,我需要生成食物并确保它与蛇不重合。这是函数定义:

Food construct_random_food(int gameSize, const Snake& snake) {
    static std::random_device rd;
    static std::uniform_int_distribution<> u(2, gameSize + 1);
    static std::default_random_engine e(rd());
    Food f;
    while (1) {
        f.x = u(e) * 2 - 1;
        f.y = u(e);
        bool coincide = 0;
        for (const auto& bd : snake) // This causes an error.
            if (bd.x == f.x && bd.y == f.y) {
                coincide = 1; break;
            }
        if (!coincide) break;
    }
    return f;
}

在基于范围的 for 循环行中导致错误。它说我正在尝试将 const Snake 转换为 Snake& (将低级 const 丢弃)。我通过像这样重写该行来解决问题:

for (const auto& fd : const_cast<Snake&>(snake))

所以我想知道 range-for 到底是做什么的以及它需要什么。错误是否与 Snake 类中的 begin() 函数有关?

【问题讨论】:

  • range-based for in c++11的可能重复
  • 请发布来自编译器的exact错误消息。
  • “导致错误...” - 当您遇到提供错误消息的问题时,始终始终将其逐字包含为你问题的一部分。我们不是读心者,不能只是猜测错误。即使我们可以猜到它,也请通过包含它来为我们省去麻烦。
  • 这是一个非常好的参考:en.cppreference.com/w/cpp/language/range-for

标签: c++ c++11 for-loop constants


【解决方案1】:

问题在于您的 beginend 函数不是 const。

auto begin()->std::deque<Body>::const_iterator const { return body.cbegin(); }
            // this applies to the return type ^^^^^

您已将 const 限定符应用于返回类型,而不是调用对象。将const 限定符放在尾随返回类型之前。

auto begin() const ->std::deque<Body>::const_iterator { return body.cbegin(); }

您可以在此处查看放置函数限定符的正确顺序:http://en.cppreference.com/w/cpp/language/function

【讨论】:

    猜你喜欢
    • 2017-07-29
    • 2015-08-26
    • 1970-01-01
    • 2012-07-23
    • 2016-09-10
    • 2023-03-15
    • 2012-10-17
    • 2021-06-04
    • 1970-01-01
    相关资源
    最近更新 更多