簡體   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