在全球范围内实例化(C++)

Sco*_*ott 1 c++ global-variables instantiation

我使用下面的代码得到以下错误.

expected constructor, destructor, or type conversion before '=' token
Run Code Online (Sandbox Code Playgroud)

-

#include <string>
#include <map>

class Foo {

};

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

int main()
{

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Ara*_*raK 13

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

直到C++ 0x成为主流,我建议使用boost.填充map成为一块蛋糕.这是一个例子:

std::map<std::string, Foo> mymap;
...
int main()
{
  insert(mymap)
   ("First",  Foo(...))
   ("Second", Foo(...))
   ("Third",  Foo(...));
   ...
}
Run Code Online (Sandbox Code Playgroud)