c++ - 将结构的枚举传递给其他函数并分配值

标签 c++ data-structures enums

我正在用 C++ 编写一个贪吃蛇游戏,我有一个蛇的部分结构,其中包含 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!

关于c++ - 将结构的枚举传递给其他函数并分配值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21269354/

相关文章:

c - 为什么*start=NULL必须在大括号外声明?我们不能写在里面吗?有什么意义吗

c++ - 初始化枚举到结构的映射

c++ - 使用 mbstowcs_s 将 char* 转换为 wchar_t*

c# - 从没有堆分配的列表中获取数组

c++ - 在使用 Clang 编译 CRTP Singleton 时,如何解决声称缺少 "explicit instantiation declaration"的问题?

c++ - 红黑树 - 旋转方法实现 - C++

c++ - C++ 枚举类型可以作为函数调用吗?或者它只是一种不同风格的转换?

c# - 带有 Type 变量的 Cast<T>()

c++ - 示例 C++ 测试

c++ - 检查无用包含文件的工具是什么?(c++)