[英]What does range-for loop exactly do?
我正在開發蛇游戲程序。 我在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))
所以我想知道范圍是做什么的,它需要什么。 該錯誤與Snake類中的begin()函數有關嗎?
問題是您的begin
和end
函數不是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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.