Player.obj :错误LNK2001:未解析的外部符号"private: static class InputHandler * InputHandler::s_pInstance"

Player.obj : error LNK2001: unresolved external symbol "private: static class InputHandler * InputHandler::s_pInstance"

本文关键字:InputHandler class static private pInstance 外部 LNK2001 错误 obj Player 符号      更新时间:2023-10-16

希望有人能帮助我这个非常微不足道的错误,我不知道如何进行:)

头文件:

#ifndef __InputHandler__
#define __InputHandler__
#include "SDL.h"
#include <SDL_image.h>
#include <vector>
#include <iostream>
enum mouse_buttons {
    LEFT = 0,
    MIDDLE = 1,
    RIGHT = 2,
};
class InputHandler {
public:
    bool getMouseButtonState(int buttonNumber) {
        return m_mouseButtonStates[buttonNumber];
    }
    std::vector<bool> m_mouseButtonStates;
    static InputHandler* Instance() {
        if (s_pInstance == 0) {
            s_pInstance = new InputHandler();
        }
        return s_pInstance;
    }
    void update();
    void clean();
private:
    InputHandler();
    ~InputHandler() {}
    static InputHandler* s_pInstance;
};
#endif

我调用InputHandler::Instance()函数在另一个类定义Player.cpp

#include "InputHandler.h"
void Player::handleInput() {
    if (InputHandler::Instance()->getMouseButtonState(LEFT)) {
        m_velocity.setX(1);
    }
}

这是我得到的错误:

Player.obj : error LNK2001: unresolved external symbol 
    "private: static class InputHandler * InputHandler::s_pInstance"

我真的不知道发生了什么,也不知道错误指向了什么。真的真的很感谢你的智慧:)))

"我真的不知道发生了什么,也不知道错误指向了什么。"

链接器错误信息告诉你丢失了什么。
现在的问题是,在翻译单元中缺少static InputHandler* s_pInstance;成员的定义。它应该看起来像这样:

InputHandler* InputHandler::s_pInstance = 0;

尽管你的单例模式有一些缺陷和不足(特别是在线程安全方面)。应该这样简化单例模式:

 static InputHandler& Instance() {
    static InputHandler theInputHandler;
    return theInputHandler; 
 }

或者如果你坚持使用指针

 static InputHandler* Instance() {
    static InputHandler theInputHandler;
    return &theInputHandler; 
 }

这通常被称为'Scott Meyer's Singleton idiom',这里有一些关于原始推理的更多信息;

c++与双重检查锁定的危险