我正在使用 GBDK C 为原版 Game Boy 创建游戏,但遇到了一个小问题。我游戏中的每个房间都需要有不同的 portal
,但每个 portal
都需要引用一个房间。这是代码的缩减版本:
typedef struct {
Portal portals[10];
} Room;
typedef struct {
Room *destinationRoom;
} Portal;
关于如何实现这一点有什么建议吗?我尝试将 struct Portal;
的前向声明添加到文件顶部,但没有帮助。
使用以下代码:
typedef struct Room Room;
typedef struct Portal Portal;
struct Room {
Portal portals[10];
};
struct Portal {
Room *destinationRoom;
};
给我这个错误:
parse error: token -> 'Room' ; column 11
*** Error in `/opt/gbdk/bin/sdcc': munmap_chunk(): invalid pointer: 0xbfe3b651 ***
最佳答案
重新排序定义并为 Room
和 Portal
类型编写前向声明:
typedef struct Room Room;
typedef struct Portal Portal;
struct Portal {
Room *destinationRoom;
};
struct Room {
Portal portals[10];
};
请注意,为了保持一致性,我将 typedef Portal
与实际的 struct Portal
定义分开,尽管这并不是绝对必要的。
另请注意,此样式与 C++ 兼容,其中 typedef 是隐式的,但可以以这种方式显式编写,或使用简单的前向声明,如 struct Room;
如果由于某种原因你不能为 struct
标签和 typedef
使用相同的标识符,你应该这样声明结构:
typedef struct Room_s Room;
typedef struct Portal_s Portal;
struct Portal_s {
Room *destinationRoom;
};
struct Room_s {
Portal portals[10];
};
关于c - GBDK C 中 typedef 结构的前向声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33059819/