繁体   English   中英

蛇游戏用 c++ OOB

[英]Snake game with c++ OOB

我在控制台的 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
};

有了这个顺序,一切都很好,但是如果我将 struct Body 和 body 的定义放在 class 之上,就像这样:

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* 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未定义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM