为什么我不能转发声明指针结构?

Why can't I forward declare pointer structs?

本文关键字:指针 结构 声明 转发 不能 为什么      更新时间:2023-10-16

我正在使用一个名为SDL_mixer的略显晦涩的声音库。GCC抱怨我正向声明了一个指针结构?我做错了什么?

Mix_Music **music; // music[2] must be a pointer to fit any random file
music = new Mix_Music[3];
music[2] = Mix_LoadMUS("fire.ogg");

GCC退货:

     ||=== Build file: "no target" in "no project" (compiler: unknown) ===|
    xxx.cpp||In function 'int SDL_main(int, char**)':|
    xxx.cpp|28|error: invalid use of incomplete type 'Mix_Music {aka struct _Mix_Music}'|
   SDL_mixer.h|131|error: forward declaration of 'Mix_Music {aka struct _Mix_Music}'|
    ||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

edit:我需要对结构进行动态分配,因为可能会加载数千个文件。堆栈内存不行。

new Mix_Music[3]中,编译器需要知道每个对象有多大,才能知道要分配多少空间。远期申报并不能提供这些信息。

您可能想要new Mix_Music*[3]。尽管堆栈分配可能会起作用,但std::arraystd::vector会使情况变得更好。