如何初始化std :: map一次,以便它可以被类的所有对象使用?

Bee*_*and 0 c++ stdmap static-members

我有一个枚举StackIndex定义如下:

typedef enum 
{
    DECK,
    HAND,
    CASCADE1,
    ...
    NO_SUCH_STACK
} StackIndex;
Run Code Online (Sandbox Code Playgroud)

我创建了一个名为的类MoveSequence,它是std::deque表单中一堆元组的包装器<StackIndex, StackIndex>.

class MoveSequence
{
    public:
        void AddMove( const tpl_move & move ){ _m_deque.push_back( move ); }
        void Print();
    protected:
    deque<tpl_move> _m_deque;
};
Run Code Online (Sandbox Code Playgroud)

我以为我可以创建一个类的静态std::map成员MoveSequence,它将a转换StackIndex为a std::string,供Print()函数使用.但是当我尝试时,我收到了错误:

"error C2864: 'MoveSequence::m' : only static const integral data members can be initialized within a class"
Run Code Online (Sandbox Code Playgroud)

如果不能将std :: map创建为静态成员,是否有另一种方法可以创建std :: map,将a StackIndex转换为std::string可用于打印MoveSequence对象的a?

谢谢

Beeband.

GMa*_*ckG 6

您需要将初始化移动到源文件中:

// header
struct foo
{
    typedef std::map<unsigned, std::string> the_map;
    static const the_map m;
};

// source
const foo::the_map foo::m(...);
Run Code Online (Sandbox Code Playgroud)

但是你需要初始化它.C++ 0x删除了此限制.

请记住Boost.Assign让这很容易:

#include <boost/assign.hpp>
const foo::the_map foo::m = boost::assign::map_list_of(1, "a")(2, "b");
Run Code Online (Sandbox Code Playgroud)