【问题标题】:std::map - C++ requires a type specifier for all declarationsstd::map - C++ 需要所有声明的类型说明符
【发布时间】:2016-03-31 04:09:55
【问题描述】:

我正在尝试填写 std::map,但出现 2 个编译器错误,我不知道是什么原因。

std::map<std::string, std::string> dirFull;
dirFull["no"] = "north";
dirFull["so"] = "south";
dirFull["ea"] = "east";
dirFull["we"] = "west";
dirFull["nw"] = "north-west";
dirFull["ne"] = "north-east";
dirFull["sw"] = "south-west";
dirFull["se"] = "south-east";

这些是错误:

error: C++ requires a type specifier for all declarations
       dirFull["no"] = "north";
       ^
error: size of array has non-integer type 'const char[3]'
       dirFull["no"] = "north";
               ^~~~


我也试过这个:
std::map<std::string, std::string> dirFull = { 
    {"no", "north"}, {"so", "south"},
    {"ea", "east"}, {"we", "west"},
    {"ne", "north-east"}, {"nw", "north-west"}, 
    {"se", "south-east"}, {"sw","south-west"} };

这会导致完全不同类型的错误:

error: non-aggregate type 'std::map<std::string, std::string>' (aka '...') cannot be initialized with an initializer list 
std::map<std::string, std::string> dirFull = {
                                   ^         ~

【问题讨论】:

  • @TonyD 我忘了补充,我用的是using namespace std;
  • 那么您可能还遗漏了其他重要的内容。请包含逐字的、未删节的代码作为最小的完整示例。
  • #include &lt;string&gt;了吗?
  • 这里没有错误。看到这个->ideone.com/RpqIhx
  • @BrianCain ,我相信我已经包含了与问题相关的所有内容。此外,这些定义在我的 file.h 文件中。它们应该在 file.cc 文件中吗?有关系吗?

标签: c++ dictionary


【解决方案1】:

您收到此错误是因为您尝试在文件范围内执行语句。在函数中定义这些赋值,你就不会再遇到这些错误了。

如果您想在静态初始化期间填充此 map,可以使用 boost::assignconstexpr 初始化语法来执行此操作。

//requires c++11:
const map <string,string> dirFull = {
    {"no",   "north"},
    {"so",   "south"},
    {"ea",   "east"},
    {"we",   "west"},
    {"nw",   "north-west"},
    {"ne",   "north-east"},
    {"sw",   "south-west"},
    {"se",   "south-east"},
};

【讨论】:

  • 如果我收到错误 non-aggregate type 'map&lt;string, string&gt;' (aka 'map&lt;basic_string&lt;char, char_traits&lt;char&gt;, allocator&lt;char&gt; &gt;, basic_string&lt;char, char_traits&lt;char&gt;, allocator&lt;char&gt; &gt; &gt;') cannot be initialized with an initializer list 是否意味着我没有使用 c++11 ?
  • @user5759490 probalby,检查你的编译器选项
  • 是的,确实如此,请确保添加-std=c++11g++clang++
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-09
  • 2017-06-05
  • 2018-03-01
  • 2022-11-14
  • 1970-01-01
相关资源
最近更新 更多