该计划有多个阶段,一个人结束时,可以选择一个新阶段。
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]
,但尚未知道。
初始化此类结构的正确方法是什么?
答案 0 :(得分:6)
在choices_p0
定义之前声明 choices_p1
和phases
数组可以轻松解决:
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
关键字,或者定义数组。
答案 1 :(得分:1)
我想说,用无效指针初始化它们,然后在分配时指定它们。
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