【发布时间】: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() 函数有关?
【问题讨论】:
-
请发布来自编译器的exact错误消息。
-
“导致错误...” - 当您遇到提供错误消息的问题时,始终始终将其逐字包含为你问题的一部分。我们不是读心者,不能只是猜测错误。即使我们可以猜到它,也请通过包含它来为我们省去麻烦。
-
这是一个非常好的参考:en.cppreference.com/w/cpp/language/range-for
标签: c++ c++11 for-loop constants