[英]Passing an enum of a structure to other functions and assigning the values
I'm writing a Snake game in C++, I have a structure for a section of the snake which contains, data such as x position, y position, direction etc. 我正在用C ++编写Snake游戏,我有一条蛇的一部分结构,其中包含诸如x位置,y位置,方向等数据。
I have it all working, setting all the data to integers, I just would like to change some of the data types to enum's because it looks a lot neater and easier to understand. 我已经全部工作了,将所有数据设置为整数,我只是想将某些数据类型更改为枚举,因为它看起来更加整洁并且易于理解。 I've tried lots and looked online but I can't seem to find anything.
我已经尝试了很多并在网上查看,但似乎找不到任何东西。
This is some of the Structure: 这是一些结构:
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
};
};
My attempt at trying to pass one of the Directions to another function: 我试图将指令之一传递给另一个功能的尝试:
void PlayerSnake::createSnake()
{
// Parameters are direction, x and y pos, the blocks are 32x32
addSection(SnakeSection::Direction::Right, mStartX, mStartY, 2);
}
Then I tried setting the direction to the one passed in in that function: 然后,我尝试将方向设置为该函数中传入的方向:
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);
}
error: invalid use of enum SnakeSection::Direction 错误:无效使用枚举SnakeSection :: Direction
Thanks 谢谢
The error on the following line ... 下一行的错误...
bufferSnake.Direction = dir;
... is reasoned, that besides declaring the enum
type, you'll still have to have a class member variable to store it: ...是有道理的,除了声明
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
};
And refer to 并参考
bufferSnake.direction_= dir; // <<<<<<<<<<<<<< THAT'S THE MEMBER VARIABLE YOU'LL
// HAVE TO REFER TO!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.