c++ - C++ 中作为类成员的静态映射

标签 c++ map static

作为 C++ 成员,我在使用静态 map 时遇到了问题。我的头文件是:

class Article
{
public:
//
static map<string,Article*> dictionary;
....
....   
};

在我的构造函数中,我首先调用了以下方法:

 void Article::InitializeDictionary()
 {
   #ifndef DICT
   #define DICT
   map<string,Article*> Article::dictionary;
   #endif
 }

根据关于此的其他帖子,我应该声明静态成员,但是当我尝试这样做时,出现以下错误:

Error   1   error C2655: 'Article::dictionary' : definition or redeclaration illegal in current scope   c:\.......\article.cpp  88  1

如果我将函数更改为以下内容:

void Article::InitializeDictionary()
{
    #ifndef DICT
    #define DICT
    Article::dictionary["null"] = 0;
    #endif
}

我收到这个错误:

Error   1   error LNK2001: unresolved external symbol "public: static class std::map<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,class Article *,struct std::less<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > >,class std::allocator<struct std::pair<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const ,class Article *> > > Article::dictionary" (?dictionary@Article@@2V?$map@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@PAVArticle@@U?$less@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@2@V?$allocator@U?$pair@$$CBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@PAVArticle@@@std@@@2@@std@@A)

对我能做什么有什么想法吗?

最佳答案

您必须正确声明和定义静态成员(在方法中这样做是错误的):

class Article
{
public:
//
static map<string,Article*> dictionary;
....
....   
};

map<string,Article*> Article::dictionary;

int main() {
    //..
}

你在评论中问过:

I tried doing this after the class declaration and got an error but if I do this in the .cpp file where the function definitions are it works. Why is that?

由于静态成员在类的所有实例之间共享,因此必须在一个且仅一个编译单元(位置)中定义它们。实际上,它们是具有一些访问限制的全局变量。

如果您尝试在 header 中定义它们,它们将在包含该 header 的每个模块中定义,并且您会在链接期间遇到错误,因为它会找到所有重复的定义。

关于c++ - C++ 中作为类成员的静态映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19336236/

相关文章:

C++ 文件 IO : read input of "29.0" to double but output is "29", 即 ".0"已删除

c++ - 查找一张 map 是否是另一张 map 的子集

map - 使用mybatis时如何从查询中更改值(null为空字符串)?

c++ - 静态函数编译器优化 C++

c# - 静态属性如何在 asp.net 环境中工作?

c++ - 将点数组转换为多边形

c++ - 使用 Xcode 和 Eclipse 在 Mac Mojave 上编译着色器问题

静态 vs 函数静态 vs 成员函数静态的 C++ 内存布局

c++ - 在单独的线程中插入时读取 std::map

c++ - 我如何找出 std::map 方法可以抛出哪些异常?