Xcode C ++ Struct Order

时间:2016-11-18 11:57:17

标签: c++ struct

由于struct的顺序,下面给出的代码不允许编译。 song_node struct包含 播放列表 变量,播放列表结构包含 song_node 变量。

此代码在Visual Studio或gcc compile上运行。

struct song_node {
    song* data;
    song_node* next;
    song_node* prev;
    playlist* parent;
};

struct playlist {
    int songnumber;
    char* name = new char[LNAME_LENGTH];
    song_node* head;
    playlist* next;
    playlist* prev;
};

我是Xcode的新手。这段代码有什么问题?

2 个答案:

答案 0 :(得分:1)

考虑类playlist前向声明

struct playlist; //Here

struct song_node {
    song* data;
    song_node* next;
    song_node* prev;
    playlist* parent;
};

struct playlist {
    int songnumber;
    char* name = new char[LNAME_LENGTH];
    song_node* head;
    playlist* next;
    playlist* prev;
};

然后编译器知道playlist,你可以在song_node中使用它,即使它尚未实现。

答案 1 :(得分:1)

你需要做一个前瞻声明。

struct playlist;

struct song_node {
    song* data;
    song_node* next;
    song_node* prev;
    playlist* parent;
};

struct playlist {
    int songnumber;
    char* name = new char[LNAME_LENGTH];
    song_node* head;
    playlist* next;
    playlist* prev;
};

当您想在playlist中使用时,编译器需要知道song_node之类的内容。通过向前声明播放列表,您可以告诉编译器存在这样的对象。