【问题标题】:How to fix error ininitialize vector of struct如何修复错误初始化结构的向量
【发布时间】:2019-01-01 05:32:10
【问题描述】:

这是我的代码。 (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"}
};

错误是

函数定义不声明参数

【问题讨论】:

  • 你必须为 5 个参数编写一个 node 构造函数。你的代码也不是 C++98。
  • @SM 谢谢。我是 C++ 新手。这段代码错了吗?
  • 这是错误的 C++98。您现在在 C++ 中使用的结构通常依赖于方言

标签: c++ vector c++98


【解决方案1】:

您可能正在使用旧的编译器,但遵循新的教程或书籍。 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 中的不同之处以避免此类问题。

【讨论】:

    猜你喜欢
    • 2014-03-06
    • 1970-01-01
    • 2011-12-25
    • 2014-05-14
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多