2011-09-15 57 views
1

問題是創建一個std::vector數據表(struct MegaTable,來自下面的示例),其中項目(struct DataItem,來自下面的示例)可能有一個指向整個數據數組的指針。如何使用指針訪問結構元素?

這裏是我的代碼:從MSVS

#include <vector> 

struct MegaDataItem; 

struct DataItem 
{ 
    int   a_; 
    char*   ch_; 

    MegaDataItem* ptr_; 

    DataItem(int _a, char* _ch, MegaDataItem* ptr) 
      : a_(_a) 
      , ch_(_ch) 
      , ptr_(ptr) 
    {} 
}; 
typedef std::vector<DataItem> DataTable; 


struct MegaDataItem 
{ 
    int   b_; 
    DataTable  data_; 

    MegaDataItem(int _b) 
      : b_(_b) 
    { 
      for (int j = 15; j >= 10; j--) 
      { 
       DataItem item(j, "", this); 
       data_.push_back(item); 
      } 
    } 
}; 
typedef std::vector<MegaDataItem> MegaTable; 


int main(int argc, char** argv) 
{ 
    MegaTable table; 

    for (int i = 0; i < 5; i++) 
    { 
      MegaDataItem megaItem(i); 
      table.push_back(megaItem); 
    } 
    return 0; 
} 

和調試快照:

enter image description here

正如你所看到的,ptr_指針處處等於0x0031fccc,但是這是不正確的!指針必須由用正確的struct MegaDataItem數據,所有struct DataItem的存在......

感謝您的幫助!

PS。我知道這不是一個很難的問題,但我無法得到它,如何讓這件事情起作用!


UPDATE(校正液): PS:thnks到jpalecek! :)

MegaDataItem(const MegaDataItem& other) 
      : b_(other.b_) 
    { 
      data_.clear(); 
      DataTable::const_iterator d_i(other.data_.begin()), d_e(other.data_.end()); 
      for (; d_i != d_e; ++d_i) 
       data_.push_back(DataItem((*d_i).a_, (*d_i).ch_, this)); 
    } 

void operator=(const MegaDataItem& other) 
    { 
      b_ = other.b_; 

      data_.clear(); 
      DataTable::const_iterator d_i(other.data_.begin()), d_e(other.data_.end()); 
      for (; d_i != d_e; ++d_i) 
       data_.push_back(DataItem((*d_i).a_, (*d_i).ch_, this)); 
    } 

回答

3

的問題是你的MegaDataItem結構是不可拷貝和分配(如果您複製或MegaDataItem分配vector,後面指針將指向原始MegaDataItem,這是不正確的)。你必須修改它。

特別是,你必須實現拷貝構造函數和賦值操作符。在這些,你必須在DataItem S中ptr_指針重定向到新MegaDataItem

實現示例:

MegaDataItem(const MegaDataItem& other) : b_(other.b_) { 
    // fill data 
    for(DataItem& item : other.data_) 
    data_.push_back(DataItem(item.a_, item.ch_, this)); 
} 

operator=(const MegaDataItem& other) { 
    b_=other.b_; 
    data_.clear(); 
    for(DataItem& item : other.data_) 
    data_.push_back(DataItem(item.a_, item.ch_, this)); 
} 

順便說一句,這取決於ch_DataItem手段,你可能想在DataItem實現這些,太。

+0

Thnks的答覆!以及如何做到這一點?我的意思是,我知道我必須重新實施copy-contructor&operator [],但是如何? – mosg

+1

請參閱編輯。請注意,這僅僅是一個例子,它可以以其他方式實施。 – jpalecek

+0

謝謝,這工作! :) – mosg

0

呃,它似乎按預期工作。您正在將this傳遞給DataItem的構造函數,因此MegaDataItem創建的所有DataItem值將共享相同的ptr_值。