簡體   English   中英

將結構的枚舉傳遞給其他函數並分配值

[英]Passing an enum of a structure to other functions and assigning the values

我正在用C ++編寫Snake游戲,我有一條蛇的一部分結構,其中包含諸如x位置,y位置,方向等數據。

我已經全部工作了,將所有數據設置為整數,我只是想將某些數據類型更改為枚舉,因為它看起來更加整潔並且易於理解。 我已經嘗試了很多並在網上查看,但似乎找不到任何東西。

這是一些結構:

struct SnakeSection
{
    int snakePosX;
    int snakePosY;

    int SectionType;
    // Tail = 0, Body = 1, Head = 2

    int animation;

  enum Direction
  {
      Up = 0,
      Right = 1,
      Down = 2,
      Left = 3
  };
};

我試圖將指令之一傳遞給另一個功能的嘗試:

void PlayerSnake::createSnake()
{
// Parameters are direction, x and y pos, the blocks are 32x32
addSection(SnakeSection::Direction::Right, mStartX, mStartY, 2);
}

然后,我嘗試將方向設置為該函數中傳入的方向:

void PlayerSnake::addSection(SnakeSection::Direction dir, int x, int y, int type)
{
    //Create a temp variable of a Snake part structure
    SnakeSection bufferSnake;

    bufferSnake.Direction = dir;
    bufferSnake.animation = 0;

    //is it head tail or what? This is stored in the Snake section struct
    //TODO Add different sprites for each section
    bufferSnake.SectionType = type;

    //assign the x and y position parameters to the snake section struct buffer
    bufferSnake.snakePosX = x;
    bufferSnake.snakePosY = y;

    //Push the new section to the back of the snake.
    lSnake.push_back(bufferSnake);
}

錯誤:無效使用枚舉SnakeSection :: Direction

謝謝

下一行的錯誤...

bufferSnake.Direction = dir;

...是有道理的,除了聲明enum類型外,您還必須具有一個類成員變量來存儲它:

struct SnakeSection
{
    int snakePosX;
    int snakePosY;

    int SectionType;
    // Tail = 0, Body = 1, Head = 2

    int animation;

  enum Direction
  {
      Up = 0,
      Right = 1,
      Down = 2,
      Left = 3
  };

  Direction direction_; // <<<<<<<<<<<<<< THAT'S WHAT'S MISSING IN YOUR CODE
};

並參考

bufferSnake.direction_= dir; // <<<<<<<<<<<<<< THAT'S THE MEMBER VARIABLE YOU'LL 
                             //                HAVE TO REFER TO!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM