如何使用指针访问结构元素?

时间:2011-09-15 12:12:30

标签: c++ pointers

问题是创建一个std::vector数据表(struct MegaTable,来自下面的示例),其中项目(struct DataItem,来自下面的示例)可以有一个指向整个数据的指针阵列。

这是我的代码:

#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;
}

从MSVS调试快照:

enter image description here

如您所见,ptr_指针到处等于 0x0031fccc ,但这不正确!指针必须包含正确的struct MegaDataItem数据,其中所有struct DataItem都存在...

感谢您的帮助!

PS。我知道这不是一个难题,但我无法理解,如何让这些事情发挥作用!


更新(更正后的解决方案): PS:对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 ) );
     }

2 个答案:

答案 0 :(得分:3)

问题是您的MegaDataItem结构不可复制且可分配(如果您在vector中复制或分配MegaDataItem,则后向指针将指向原始MegaDataItem ,这是不正确的)。你必须修改它。

特别是,您必须实现复制构造函数和赋值运算符。在这些内容中,您必须将ptr_中的DataItem指针重定向到新的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));
}

BTW,取决于ch_DataItem的含义,您也可以在DataItem中实现这些内容。

答案 1 :(得分:0)

呃,似乎按预期工作了。您正在将this传递给DataItem的构造函数,因此DataItem创建的MegaDataItem所有ptr_将共享相同的{{1}}值。< / p>
相关问题