2017-08-24 42 views
3

所以我很新的C(和一般节目),我想使用结构作为值枚举枚举与结构作为值?

typedef struct { 
    int x; 
    int y; 
} point; 

// here's what I'd like to do 
enum directions { 
    UP = point {0, 1}, 
    DOWN = point {0, -1}, 
    LEFT = point {-1, 0}, 
    RIGHT = point {1, 0} 
}; 

这样以后我可以用枚举进行坐标转换

如果你明白我想达到的目标,请你解释为什么这不起作用和/或什么是正确的方法来做到这一点?

回答

6

enum仅用于将“幻数”翻译成文字和有意义的内容。它们只能用于整数。

你的例子比这更复杂。看起来你真正在寻找的是一个结构体,它包含4个不同的point成员。可能const合格。例如:

typedef struct { 
    int x; 
    int y; 
} point; 

typedef struct { 
    point UP; 
    point DOWN; 
    point LEFT; 
    point RIGHT; 
} directions; 

... 

{ 
    const directions dir = 
    { 
    .UP = (point) {0, 1}, 
    .DOWN = (point) {0, -1}, 
    .LEFT = (point) {-1, 0}, 
    .RIGHT = (point) {1, 0} 
    }; 
    ... 
} 
3

不,枚举只是整型常量的集合。接近你想要什么(点类型的常量表达式)的一种方法是用预处理器和复合文字:

#define UP (point){0, 1} 
#define DOWN (point){0, -1} 
#define LEFT (point){-1, 0} 
#define RIGHT (point){1, 0} 

,如果你不链接到C的过时版本的一些愚蠢的原因,这只会工作,因为复合文字是在C99中添加的。

+0

注意术语“ANSI C”早已过时,有时混淆这些天。 –

+0

@ P.P。 - 这主要是因为一些人声称他们无论如何都不能使用现代C – StoryTeller

+1

理由有时并不愚蠢,人们被编译器/版本困住,因为变化可能会影响数百万人的欢呼;) – P0W

1

enum s是整数,没有什么更少的了,通过defintion。

一种可能的方式来实现你可能想可能是什么:

enum directions { 
    DIR_INVALID = -1 
    DIR_UP, 
    DIR_DOWN, 
    DIR_LEFT, 
    DIR_RIGHT, 
    DIR_MAX 
}; 

typedef struct { 
    int x; 
    int y; 
} point; 

const point directions[DIR_MAX] = { 
    {0, 1}, 
    {0, -1}, 
    {-1, 0}, 
    {1, 0} 
}; 

#define UP directions[DIR_UP] 
#define DOWN directions[DIR_DOWN]  
#define LEFT directions[DIR_LEFT] 
#define RIGHT directions[DIR_RIGHT]