I am writing a simple logging class with C++. I want to create an unordered_map to store logging_levels, but compiling fails.
#include <iostream>
#include <unordered_map>
#include <string>
class logging {
public:
std::unordered_map<std::string, int> m_log_levels;
m_log_levels["info"] = 2;
m_log_levels["warning"] = 1;
m_log_levels["error"] = 0;
private:
int m_level = m_log_levels["info"];
public:
void setLevel(int level) {
m_level = level;
}
void warn(const char* message) {
std::cout << message << std::endl;
}
};
>Solution :
You can’t put arbitrary code wherever you want in a class definition.
Initialize the hash table in a constructor i.e.
class logging {
public:
std::unordered_map<std::string, int> m_log_levels;
private:
int m_level;
public:
logging() { // <<< this is a constructor...
m_log_levels["info"] = 2;
m_log_levels["warning"] = 1;
m_log_levels["error"] = 0;
m_level = m_log_levels["info"];
}
void setLevel(int level) {
m_level = level;
}
void warn(const char* message) {
std::cout << message << std::endl;
}
};