初始化静态地图,不知道密钥

initialize a static map without know the key

本文关键字:不知道 密钥 地图 静态 初始化      更新时间:2023-10-16

是否可以初始化静态地图而不知道键?

我有一个我使用

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

,所以我需要在此类中初始化它,但是由于我不知道对象的内容objclass,我得到了错误:

undefined reference to A::n_map

我该如何解决?

静态类数据成员需要定义并被声明。初始化器可以使用非恒定表达构件的定义,也可以使用恒定表达的声明。

例如:

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" }
                                        };