如何修复错误初始化结构向量

时间:2019-01-01 05:32:11

标签: c++ vector c++98

这是我的代码。 (C ++ 98)

struct node
{
    string name;
    string help;
    string action;
    string pName;
    string pHelp;
};

vector<node> commands {
    node{"name1", "help1", "", "", ""},
    node{"name2", "help2", "action2", "pname", "phelp"}
};

错误是

  

函数定义未声明参数

1 个答案:

答案 0 :(得分:3)

您可能正在使用旧的编译器,但遵循新的教程或书籍。 gcc 5.4.0给出了这一点:

test.cpp:12:27: warning: extended initializer lists only available with -std=c++11 or -std=gnu++11
    vector <node> commands {
                           ^
test.cpp:13:10: warning: extended initializer lists only available with -std=c++11 or -std=gnu++11
      node{"name1","help1", "", "" , ""}, node{"name2", "help2","action2",    "pname", "phelp"}
          ^
test.cpp:13:46: warning: extended initializer lists only available with -std=c++11 or -std=gnu++11
      node{"name1","help1", "", "" , ""}, node{"name2", "help2","action2",    "pname", "phelp"}
                                              ^
test.cpp:14:6: error: in C++98 ‘commands’ must be initialized by constructor, not by ‘{...}’
      };

显然,您要么至少必须使用c ++ 11,要么需要为node提供一个带有五个参数并使用旧样式构造对象的构造函数。

除非您有非常特定的理由坚持使用c ++ 98,否则我会说转向C ++ 11是最佳选择。否则,请遵循教C ++ 98的书籍或教程,或者至少描述C ++ 98中的不同之处以避免此类问题。