c++ - 在静态函数中使用静态变量的问题

标签 c++

我有一个完整的静态类,使用 std::map

这是简化的情况

.h

#ifndef KEYBOARD_H
#define KEYBOARD_H

#include <map>

class Keyboad {

    static std::map<char, bool> pressed;    

    static void keyPressedEvent(char _key); 

};

#endif

.cpp

#include "Keyboard.h"

void Keyboard :: keyPressedEvent(char _key) {

    Keyboard :: pressed[_key] = true;

}

但是静态成员变量有问题,因为我得到

Undefined symbols:
"Keyboard::pressed", referenced from:
__ZN15Keyboard7pressedE$non_lazy_ptr in Keyboard.o
(maybe you meant: __ZN15Keyboard7pressedE$non_lazy_ptr)
ld: symbol(s) not found
collect2: ld returned 1 exit status

当我删除它时,它运行正常

为什么会出现这个问题,使用静态变量应该没有问题:/

谢谢

最佳答案

您需要在 .cpp 文件中定义 pressed map :

#include "Keyboard.h"
std::map<char, bool> Keyboard::pressed;

// The rest as before

关于c++ - 在静态函数中使用静态变量的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6828049/

相关文章:

C++ - 在 main() 函数中定义变量时遇到问题

c++ - 为什么我不能在 C++ 中从单个字符构造 std::string?

c++ - 常见问题 TDD with Mock

c++ - 为什么在这种特殊情况下数据类型会影响性能?

c++ - omp 有序子句如何工作?

c++ - 静态库中对 c++11 原子的 undefined reference

c++ - 如何从霍夫曼树生成霍夫曼码

c++ - 如何有效地将 if 和 else 用于过滤结构?

c++ - UTF8 字符是否有分隔符字节?

c++ - 二叉树,其中每个节点的值保存子节点的总和