我有一个完整的静态类,使用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
Run Code Online (Sandbox Code Playgroud)
的.cpp
#include "Keyboard.h"
void Keyboard :: keyPressedEvent(char _key) {
Keyboard :: pressed[_key] = true;
}
Run Code Online (Sandbox Code Playgroud)
但是静态成员变量存在问题,因为我得到了
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
Run Code Online (Sandbox Code Playgroud)
当我删除它,它运行正常
为什么我会遇到这个问题,使用静态变量时应该没有问题:/
谢谢
您需要pressed
在.cpp文件中定义地图:
#include "Keyboard.h"
std::map<char, bool> Keyboard::pressed;
// The rest as before
Run Code Online (Sandbox Code Playgroud)
您应该将其添加到.cpp文件中
std::map<char, bool> Keyboad::pressed;
Run Code Online (Sandbox Code Playgroud)
将静态类成员视为全局变量.编译器应该在唯一的目标文件中为它们分配内存.所以你应该在相应的源文件中定义它们.
归档时间: |
|
查看次数: |
165 次 |
最近记录: |