在不知道密钥的情况下初始化静态地图

时间:2014-01-26 15:40:16

标签: c++ c++11 static-members

是否有可能在不知道密钥的情况下初始化静态地图?

我有一个A级,我要使用

static std::map<ObjClass *, int> n_map; 

所以我需要在这个类中初始化它,但由于我无法知道对象ObjClass的内容,我得到了错误:

undefined reference to A::n_map

我怎么解决?

1 个答案:

答案 0 :(得分:0)

静态类数据成员需要定义以及声明。初始化程序可以使用非常量表达式成员的定义,也可以使用常量表达式的声明。

例如:

<强> foo.h中:

#include <map>
#include <string>

struct Foo
{
    // declaration and initializer
    static constexpr int usageCount = 0;

    // only declaration
    static const double val1;
    static       double val2;

    // only declaration
    static std::map<int, std::string> theMap;
};

<强> Foo.cpp中:

#include <foo.h>

// only definition (only required if ODR-used)
constexpr int Foo::usageCount;

// definition and initializer (initializer required, since const)
const double Foo::val1 = 1.5;

// only definition (implicitly statically-initialzied (i.e. zeroed))
double Foo::val2;

// definition and initializer
std::map<int, std::string>> Foo::theMap { { 1, "abc" }
                                        , { 2, "def" }
                                        };