gpt4 book ai didi

c++ - range-for 循环到底做了什么?

转载 作者:太空宇宙 更新时间:2023-11-04 15:32:44 24 4
gpt4 key购买 nike

我正在开发贪吃蛇游戏程序。我在 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() 函数有什么关系吗?

最佳答案

问题是您的 beginend 函数不是常量。

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

关于c++ - range-for 循环到底做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45639913/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com