Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

unordered_map inside C++ class

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
    }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading