我有一个完整的静态类,使用 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/