[英]Initializing two arrays of structs referencing each other
該計划有多個階段,一方面,我們可以選擇一個新的階段。
struct PhaseChoice;
struct Phase {
PhaseChoice* choices;
};
struct PhaseChoice {
bool (*condition)();
Phase* newPhase;
};
......這個前瞻性聲明沒問題。 但我無法初始化它。
Phase phases[2] = {
{ choices_p0 },
{ choices_p1 }
}
PhaseChoice choices_p0[2] = {
{ condition_p0p1,
&phases[1] },
{ condition_p0again,
&phases[0] },
};
PhaseChoice choices_p1[2] = {
{ condition_p1p0,
&phases[0] },
{ condition_p1again,
&phases[1] },
};
這顯然是失敗的,因為在初始化phases[2]
,程序仍然沒有關於choices_p0
或choices_p1
線索。 如果我顛倒了順序,初始化choices_p0
我會遇到&phases[1]
,這是未知的。
初始化這種結構的正確方法是什么?
可以通過在phases
定義之前聲明 choices_p0
和choices_p1
數組來輕松解決:
extern PhaseChoice choices_p0[2];
extern PhaseChoice choices_p1[2];
Phase phases[2] = {
{ choices_p0 },
{ choices_p1 }
};
PhaseChoice choices_p0[2] = { ... };
PhaseChoice choices_p1[2] = { ... };
您需要聲明的extern
關鍵字,或者您定義數組。
我會說,用無效指針初始化它們,然后分配它們。
Phase phases[2] = {
{ nullptr },
{ nullptr }
}
PhaseChoice choices_p0[2] = {
{ condition_p0p1,
&phases[1] },
{ condition_p0again,
&phases[0] },
};
PhaseChoice choices_p1[2] = {
{ condition_p1p0,
&phases[0] },
{ condition_p1again,
&phases[1] },
};
phases[0] = choices_p0;
phases[1] = choices_p1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.