初始化两个引用彼此的结构数组

时间:2015-07-08 16:05:32

标签: c++ struct initialization

该计划有多个阶段,一个人结束时,可以选择一个新阶段。

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_p0choices_p1。如果我撤消订单,请初始化choices_p0我会遇到&phases[1],但尚未知道。

初始化此类结构的正确方法是什么?

2 个答案:

答案 0 :(得分:6)

choices_p0定义之前声明 choices_p1phases数组可以轻松解决:

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