How to initialize private static members in C++?

后端 未结 17 2261
忘掉有多难
忘掉有多难 2020-11-21 07:04

What is the best way to initialize a private, static data member in C++? I tried this in my header file, but it gives me weird linker errors:

class foo
{
           


        
17条回答
  •  感情败类
    2020-11-21 07:10

    Does this serves your purpose?

    //header file
    
    struct MyStruct {
    public:
        const std::unordered_map str_to_int{
            { "a", 1 },
            { "b", 2 },
            ...
            { "z", 26 }
        };
        const std::unordered_map int_to_str{
            { 1, "a" },
            { 2, "b" },
            ...
            { 26, "z" }
        };
        std::string some_string = "justanotherstring";  
        uint32_t some_int = 42;
    
        static MyStruct & Singleton() {
            static MyStruct instance;
            return instance;
        }
    private:
        MyStruct() {};
    };
    
    //Usage in cpp file
    int main(){
        std::cout<

提交回复
热议问题