在实现了这个线程中建议的数据结构之后,我决定用一些测试值来填充它。
代码是
typedef enum {car, gun, bullet} itemtype;
typedef struct bullettype {
unsigned short velocity;
unsigned short kinetic_energy;
} Bullet;
typedef struct cartype {
unsigned short maxspeed;
} Car;
typedef enum {handgun, shotgun, machinegun} weapontype;
typedef struct firearmtype {
weapontype type;
char capacity;
} Firearm;
typedef struct gameitem {
itemtype type;
char* name;
unsigned short bulk;
unsigned short weight;
union {
Car c;
Bullet b;
Firearm f;
};
} Item;
int main() {
Item *objects = malloc(50 *sizeof(Item));
objects[0] = (Item) {gun, "a gun", 500, 5000, (Firearm) {handgun, 10}};
objects[1] = (Item) {car, "a car", 3500, 4000, (Car) {200}};
objects[2] = (Item) {bullet, "a bullet", 200, 3000, (Bullet) {300, 5000}};
free(objects);
return 0;
}
但是当我编译它时,我得到
itemlisttest.c:40:2: error: incompatible types when initializing type ‘short unsigned int’ using type ‘Firearm’
itemlisttest.c:42:3: error: incompatible types when initializing type ‘short unsigned int’ using type ‘Bullet’
这意味着该car
项目工作正常。它在结构内的联合中首先列出。所以我决定像这样在联盟中交换Car和Bullet
union {
Bullet b;
Car c;
Firearm f;
};
编译器错误现在是
itemlisttest.c:40:2: error: incompatible types when initializing type ‘short unsigned int’ using type ‘Firearm’
itemlisttest.c:41:2: error: incompatible types when initializing type ‘short unsigned int’ using type ‘Car’
这与我初始化结构的方式有关吗?我这样做是因为这将是一个很长的列表,而且 1000object[a].name = "name"
行看起来一点也不漂亮。