我如何访问枚举中的变量
Posted
技术标签:
【中文标题】我如何访问枚举中的变量【英文标题】:how can i access a variable in enum 【发布时间】:2022-01-12 15:38:03 【问题描述】:#define NUMBER_OF_CARDS 54
typedef enum type
QUEEN;
JACK;
KING
CardTypes;
typedef struct game
CardTypes cards[NUMBER_OF_CARDS];
struct
int hearts;
int spades;
int clubs;
int diamonds;
int players_cards;
GameState;
我有类似的东西,我想在调用此函数时从enum
访问任何变量
void set_cards(GameState gamestate, int x, int y, CardTypes cardtypes)
gamestate.cards[x * y] = cardtypes;
void generate_game(GameState gamestate)
/*
some code
*/
if(variable == 0)
set_cards(gamestate, x, y, gamestate.cards[NUMBER_OF_CARDS].JACK;
//This is what I have tried but it doesn't work
我希望你明白我的意思,因为我真的不知道如何更好地解释这一点。
set_cards(gamestate, x, y, gamestate.cards[NUMBER_OF_CARDS].JACK;
//this is what I have tried but it doesn't work
请忽略代码中的任何不准确之处。对我来说重要的是如何访问函数 generate_game() 中的任何枚举变量。
就在这里:if(variable == 0) set_cards(gamestate, x, y, gamestate.cards[NUMBER_OF_CARDS].JACK; //This is what I have tried but it doesn't work
【问题讨论】:
cards 是一个整数数组(枚举)。并且整数没有任何成员,所以 '.'运营商将无法工作。正如阿空加瓜所说,您的索引超出了范围。 枚举值实际上只是常量,在这方面它们与整数文字没有区别。QUEEN == 0
,JACK == 1
,KING == 2
。 int n = QUEEN;
与 int n = 0;
没有区别,您希望如何访问它们?
也许你有一个根本的误解:enum
s 不像像struct
s - 他们是一堆常量,仅此而已,结构中没有成员变量。等效地,您可以简单地完成:#define QUEEN 0 #define JACK 1 #define KING 2
,但枚举使您不必单独定义值。
@r3k0j 77.JACK
是什么意思?除了您正在尝试做的具体价值之外。如果你想检查一个位置是否包含一个值,然后比较:if(gamestate.cards[0] == JACK) ...
——注意双等号,与我的第一条评论相反。
等一下——您只是想将JACK
的值传递给函数,对吗?然后就简单多了:set_cards(game_state, x, y, JACK);
– 枚举常量与整个枚举的作用域完全相同...
【参考方案1】:
你的类型没有太多意义。卡片由其颜色和类型定义。
typedef enum
QUEEN,
JACK,
KING,
//you neeed some more
CardTypes;
typedef enum
HEART,
SPADE,
CLUB,
DIAMOND,
CardColour;
typedef struct
CardTypes type;
CardColur colour;
Card;
Card deck[54];
如何访问:
void foo(Card *card)
Card card1;
card1.colour = HEART;
card1.type = JACK;
card -> colour = DIAMOND;
card -> type = KING;
card[34].colour = CLUB;
card[34].type = QUEEN;
【讨论】:
我看到的术语是"suit" and "rank",而不是“颜色”和“类型”。 (不是反对者)【参考方案2】:根据@Aconcagua 编写的代码,您的代码应该使用指针:
// gamestate is a structure , so it must be passed as pointer to enable modification to be seen by caller
void set_cards(GameState *gamestate, int x, int y, CardTypes cardtypes)
gamestate->cards[x * y] = cardtypes;
void generate_game(GameState *gamestate) // here also pointer so caller know the changes
/*
some code
*/
if(variable == 0)
// next depends on what you intend to do :
// 1- set the current games rate card with value of last card
set_cards(gamestate, x, y, gamestate->cards[NUMBER_OF_CARDS-1]);
// 2- set the current gamestate to JACK
set_cards(gamestate, x, y, JACK);
【讨论】:
以上是关于我如何访问枚举中的变量的主要内容,如果未能解决你的问题,请参考以下文章