gpt4 book ai didi

c++ - 使用 C++ OOB 的贪吃蛇游戏

转载 作者:行者123 更新时间:2023-11-27 23:37:45 45 4
gpt4 key购买 nike

我在控制台中用 C++ 编写了一个贪吃蛇游戏,但遇到了一些我无法理解的问题。谁能帮帮我?根据以下代码:

class Snake : public Fruit{
private:
int head;
short dir_x; //-1 (left or down) / +1 (right or up)
short dir_y;

friend class Game;

int base_length = 3; // base length of snake on start of the game
const int length = Board::global_x * Board::global_y; // max length
int prev_tailPos[2]; // previous tail position (end of snake)
int tail; // tail is sum of base_length and score
int time = 100; // delay for snake

struct Body{
int body_pos[2]; // position of every element of snakes body
Body* higherEl; // point element nearer head element
};
Body* body = new Body[length]; // array for body of snake
};

按照这个顺序一切都很好,但是如果我把结构体的定义和主体放在那个类的顶部,就像那样:

class Snake : public Fruit{
private:
struct Body{
int body_pos[2]; // position of every element of snakes body
Body* higherEl; // point element nearer head element
};
Body* body = new Body[length]; // array for body of snake

int head;
short dir_x; //-1 (left or down) / +1 (right or up)
short dir_y;

friend class Game;

int base_length = 3; // base length of snake on start of the game
const int length = Board::global_x*Board::global_y; // max length
int prev_tailPos[2]; // previous tail position (end of snake)
int tail; // tail is sum of base_length and score
int time = 100; // delay for snake
};

在我停止游戏后出现此错误:

> Unhandled Exception at 0x76C40860 (sechost.dll) in Snake.exe: 
> 0xC0000005: Access violation reading location 0x00000004`

谁能帮我解决这个问题?

最佳答案

在你的第二个例子中,变量 length 在评估时似乎是未定义的
正文* body = new Body[length];

这很可能是您的问题。

为了进一步解释这一点,您需要了解:
类/结构中变量声明的顺序很重要

举例说明:

class Data{
int a = 10;
int b = a;
};

在此示例中,ab 都将等于 10。
但是,在这种情况下:

class Data{
int b = a;
int a = 10;
};

a 将是 10,b 将是垃圾值。
这是因为在评估 int b = a; 时。 a 未定义。

关于c++ - 使用 C++ OOB 的贪吃蛇游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58014059/

45 4 0
文章推荐: C++ if语句使用lambda表达式返回true但输出来自false,为什么
文章推荐: html - 在