0

I created a singleton containing a map of string,bool pairs for storing when a key is pressed on the keyboard.

I have the following header file:

#pragma once

#include <unordered_map>
#include <iostream>
#include <string>

using namespace std;

// Singleton service that stores keypresses during frame

class KeyboardService
{
private:
    static KeyboardService* instance;

    unordered_map<string, bool> keys =
    {
        {"up", 0},
        {"down", 0},
        {"left", 0},
        {"right", 0},
        {"one", 0},
        {"two", 0},
        {"three", 0},
        {"d", 0}
    };

    KeyboardService(){};

public:
    static KeyboardService* getInstance();

    bool isPressed(string input);
    void pressKey(string input);
    void unpressKey(string input);

};

And implementation:

#pragma once

#include "keyboard_service.hpp"

KeyboardService* KeyboardService::instance = 0;

unordered_map<string, bool> keys;

KeyboardService* KeyboardService::getInstance()
{
    if(!instance)
    {
        instance = new KeyboardService;
    }
    return instance;
}

bool isPressed(string input)
{
    return keys[input];
}

void pressKey(string input)
{
    keys[input] = 1;
}

void unpressKey(string input)
{
    keys[input] = 0;
}

When I try to use these functions, I get an error:

"KeyboardService::isPressed(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >)", referenced from:
      UserInputSystem::update(float) in user_input_system.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
Mr. Kaplan
  • 53
  • 2
  • 8

1 Answers1

3
bool isPressed(string input)
{
    return keys[input];
}

void pressKey(string input)
{
    keys[input] = 1;
}

void unpressKey(string input)
{
    keys[input] = 0;
}

You defined a few free functions, and those have nothing to do with the class member functions. You have to specify that they are member functions of KeyboardService:

bool KeyboardService::isPressed(string input)
{
    return keys[input];
}

void KeyboardService::pressKey(string input)
{
    keys[input] = 1;
}

void KeyboardService::unpressKey(string input)
{
    keys[input] = 0;
}
ph3rin
  • 4,426
  • 1
  • 18
  • 42