I have been trying to make a StringTable class that holds a simple unordered_map<string, string>, and has the array index operator ‘[]’ overloaded to work for accessing the map; however, the compiler will tell me that I have yet to define the overloaded operator when I try to use it. My code is as follows:
CStringTable.h
#include <string>
#include <fstream>
#include <tr1/unordered_map>
class CStringTable {
public:
bool Load(const char* filename);
inline const char* operator [](const char* key);
const char* Get(const char* key);
private:
std::tr1::unordered_map<std::string, std::string>* m_StringMap;
};
CStringTable.cpp
#include "CStringTable.h"
inline const char* CStringTable::operator [](const char* key) {
std::string sKey = key;
return (*m_StringMap)[sKey].c_str();
}
I try to access the map as follows:
(*m_cStringTable)[msgKey]
where m_cStringTable is a pointer to an instance of the CStringTable class and msgKey is a const char*.
Can anybody enlighten me as to why this won’t work?
Regarding the inline keyword, the compiler needs to be able to see the body of that method as well in the .h file. So either move the implementation of the operator from the .cpp file to the .h file, or include the body of the operator in the class declaration.