嘿伙计们,我只能找到在枚举上使用 rand() 的 C++ 示例。我想从我的枚举中获取白色或红色的随机颜色,然后为结构体播放器中的 thiscolor 变量提供颜色。
到目前为止我已经得到了这个-
enum cell_contents
{
/** the cell does not contain a token **/
C_EMPTY,
/** the cell contains a red token **/
C_RED,
/** the cell contains a white token **/
C_WHITE
};
typedef enum cell_contents color;
然后我有一个结构 -
struct player
{
/**
* the player's name
**/
char name[NAMELEN+2];
/**
* the color of the token for the player. Note: this is a typedef of
* enum @ref cell_contents.
**/
color thiscolor;
/**
* how many counters does this player have on the board?
**/
unsigned counters;
/**
* what type of player is this? A human or a computer?
**/
enum playertype type;
};
然后在一个初始化结构体中所有值的函数中
enum input_result get_human_player(struct player* human)
{
human->thiscolor = color(rand() % 2);
}
但是它只是给了我一个错误,说“意外的类型名称'颜色':预期的表达式”。我也尝试过只使用:
human->thiscolor = enum cell_contents(rand() % 2);
还有
human->thiscolor = enum color(rand() % 2);
但是这两个也不起作用?
最佳答案
color
是一个类型(或者更确切地说是类型别名),并且不能像函数一样使用。我认为您在 C 代码中混合了其他语言(也许是 C++?)
在 C 中,任何 int
都可以隐式转换为枚举,因此只需执行例如
human->thiscolor = rand() % 2;
应该可以正常工作。
如果想将整数显式转换为 color
类型,则执行
human->thiscolor = (color) (rand() % 2);
关于c - 获取枚举的随机值并保存到指针结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32068483/