static map initialization

后端 未结 2 1483
南方客
南方客 2020-12-16 11:59

I have the following code :I have the following code:

//MyClass.h
class MyClass {
public:
      typedef std::map OpMap;
      static          


        
相关标签:
2条回答
  • 2020-12-16 12:15

    If you're using C++11, you could use initializer lists:

    //MyClass.h
    class MyClass {
    public:
          typedef std::map<std::string, int> OpMap;
          static OpMap opMap_;
    };
    
    //MyClass.cpp
    MyClass::OpMap MyClass::opMap_ = { 
        { "x", 1 }
    }; 
    

    If you don't have access to a compiler that supports the C++11 standard, you could do the following:

    //MyClass.h
    class MyClass {
    public:
          typedef std::map<std::string, int> OpMap;
          static OpMap opMap_;
    private:
          static OpMap init_map() {
              OpMap some_map;
              some_map["x"] = 1;
              return some_map;
          }
    };
    
    //MyClass.cpp
    MyClass::OpMap MyClass::opMap_ = init_map();
    
    0 讨论(0)
  • 2020-12-16 12:15

    As you are using VS2010, you need to initialize your static member in MyClass.cpp, in front of any other member function definitions. call MyClass::InitMap() if you want to initialize opMap_.

    MyClass.h

    class MyClass
    {
    public:
      MyClass(void);
      ~MyClass(void);
    public:
       typedef std::map<std::string, int> OpMap;
       static OpMap opMap_;    
       static void InitMap();
    };
    

    MyClass.cpp

    std::map<std::string, int> MyClass::opMap_;
    MyClass::MyClass(void)
    {
       InitMap(); // just sample if you want to initialize opMap_ inside MyClass constructor
    }
    
    void InitMap()
    {
      MyClass::opMap_["x"] = 1;
    }
    
    0 讨论(0)
提交回复
热议问题