1

下面的代码出现以下错误。

expected constructor, destructor, or type conversion before '=' token

--

#include <string>
#include <map>

class Foo {

};

std::map<std::string, Foo> map;
map["bar"] = Foo();

int main()
{

    return 0;
}
4

3 回答 3

13
map["bar"] = Foo(); // This line is a statement not a declaration.
                    // You have to put it in main, or any execution context

在 C++0x 成为主流之前,我建议使用boost. 填充map成为小菜一碟。这是一个例子:

std::map<std::string, Foo> mymap;
...
int main()
{
  insert(mymap)
   ("First",  Foo(...))
   ("Second", Foo(...))
   ("Third",  Foo(...));
   ...
}
于 2009-10-26T23:14:30.020 回答
4

如您所见,简短的回答是:您不能那样做。

我认为您真正想要的是:

std::map<std::string, Foo> map;

int main()
{
    map["bar"] = Foo();

如果你真的需要初始化之前main()你会经常看到这样的例子:

namespace {
   struct StaticInitHelper {
       StaticInitHelper() { map["bar"] = Foo(); }
   } _helper_obj;
}

但是,现在您遇到了一个新问题,即无法保证map之前创建的_helper_obj. 解决此问题的一种方法是将它们组合起来:

namespace {
   struct StaticInitHelper : public std::map<std::string, Foo> {
       StaticInitHelper() { (*this)["bar"] = Foo(); }
   } map;
}

但是,通常不建议从 STL 容器类继承。请注意,此示例隐藏了任何其他构造函数,并且 STL 基类没有虚拟析构函数。这将被许多人视为“黑客”,应该真正避免。

另一种选择是用 a 定义类std::map

namespace {
   struct StaticInitHelper {
       StaticInitHelper() { map["bar"] = Foo(); }
       std::map<std::string, Foo> map;
   } map_holder;
}

map_holder.map.find(...

但这当然会使地图的任何使用变得复杂。

更新:

我忘了提到另一个选项,使用boost::assign

#include <boost/assign/list_of.hpp>

map<int,int> map = boost::assign::map_list_of(1,2)(2,3)(3,4)(4,5)(5,6);

不过,我找不到关于这在静态对象上是否安全的信息。

于 2009-10-26T23:27:33.813 回答
1

看起来你想要的是一个静态初始化程序。我建议你阅读这个。它说明了静态初始化器的使用以及它们的主要缺陷,静态初始化顺序。

于 2009-10-26T23:21:24.607 回答