2016-04-10 11 views
2

マルチマップで動作する構造とメソッドを持つクラスを記述します。 addItemToList-方法は、マルチマップで構造を追加するとsaveListData-方法は、バイナリファイルに保存します:C++:マルチマップ静的変数に格納されたデータへのアクセス方法

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メソッドのローカルスコープでマルチマップを宣言しました。クラスのさまざまなメソッドでアクセスする場合は、クラススコープで宣言して定義する必要があります。

さらに、メモリリークを防ぐために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(); 
} 
関連する問題