2016-04-10 77 views
2

我寫了一個具有結構和一些可以與multimap一起使用的方法的類。該addItemToList法將在多重映射添加結構和saveListData法將其存儲在一個二進制文件:C++:如何獲取存儲在multimap靜態變量中的數據

class listData 
{ 
public: 
    struct ItemStruct 
    { 
     long int item_id; 
     int ess_id; 
     char item_type; 
     char list_type; 
     time_t add_date; 
    }; 
    int addItemToList(long int item_id, char list_type, char item_type = '\0', int ess_id = 0) 
    {   
     ItemStruct *pAddingItem = new ItemStruct; 
     pAddingItem->item_id = item_id; 
     pAddingItem->list_type = list_type; 
     pAddingItem->item_type = item_type; 
     pAddingItem->ess_id = ess_id; 
     pAddingItem->add_date = std::time(nullptr); 
     typedef std::multimap<char, struct ItemStruct> ListDataMap; 
     static ListDataMap container; 
     container.insert(std::pair<char, struct ItemStruct>(list_type, *pAddingItem)); 
    return 0; 
    } 

    int saveListData() 
    { 
     // how can I access to data stored in the container static variable? 
    return 0; 
    }   
}; 

,並使用下一個代碼類:

#include <ctime> 
#include <iostream> 
#include <map> 
#include "lists.cpp" 
using namespace std; 

int main(int argc, char** argv) 
{ 
    listData test; 
    test.addItemToList(10, 's', 'm', 1555); 
    test.addItemToList(10, 'c', 'm', 1558); 

    test.saveListData(); 
} 

我如何可以訪問數據存儲在容器中的靜態變量?

回答

0

在您的代碼中,您已經在方法addItemToList的本地範圍內聲明瞭您的multimap,而不是在類範圍內。當你想用你的類的各種方法訪問它時,你必須在類作用域聲明和定義它。

此外,我調整了addItemToList實現的內容以避免內存泄漏。

爲簡單起見,我把一切都放在一個文件:

#include <ctime> 
#include <iostream> 
#include <map> 
using namespace std; 

class listData 
{ 
    private: 
     struct ItemStruct 
     { 
      long int item_id; 
      int ess_id; 
      char item_type; 
      char list_type; 
      time_t add_date; 
     }; 

     typedef std::multimap<char, struct ItemStruct> ListDataMap; 
     static ListDataMap container; // multimap declaration 

    public: 
     int addItemToList(long int item_id, char list_type, char item_type = '\0', int ess_id = 0) 
     {   
      ItemStruct pAddingItem; 
      pAddingItem.item_id = item_id; 
      pAddingItem.list_type = list_type; 
      pAddingItem.item_type = item_type; 
      pAddingItem.ess_id = ess_id; 
      pAddingItem.add_date = std::time(nullptr); 
      container.insert(std::pair<char, struct ItemStruct>(list_type, pAddingItem)); 
      return 0; 
     } 

     int saveListData() 
     { 
      // use container here 
      // container.<whatever-method> 
      return 0; 
     }   
}; 

listData::ListDataMap listData::container; // multimap definition 

int main(int argc, char** argv) 
{ 
    listData test; 
    test.addItemToList(10, 's', 'm', 1555); 
    test.addItemToList(10, 'c', 'm', 1558); 

    test.saveListData(); 
} 
相關問題