gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:05:49 25 4
gpt4 key购买 nike

问题是创建一个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:感谢 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 ) );
}

最佳答案

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

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

顺便说一句,根据 DataItem 中的 ch_ 的含义,您可能还想在 DataItem 中实现这些。

关于c++ - 如何使用指针访问结构元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7430593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com