我已经做了好几天了,我似乎不明白为什么我的最后两件事不会打印出来。代码很长,所以我不会全部发布,但如果你需要,我愿意提供整个源代码。
基本上,我在为每个列出的元素添加1个元素后调用print函数。除了最后两个"配偶"one_answers"孩子"外,它将打印所有内容。这两个是最复杂的,因为它们也是自己的列表。当我为child测试for循环时,它表明无论我向Vector添加多少个child,它读取的大小都是0。为什么会这样?
void AddressNode::PrintFull()
{
cout << setfill(' ') << endl;
cout << setw(15) << "UID " << "ID" << setfill('0') << setw(3) << id_ << setfill(' ')<< endl;
cout << setw(15) << "NAME:" << firstName_ << " " << lastName_ << endl;
cout << setw(15) << "Address1:" << address_ << endl;
cout << setw(15) << "City:" << city_<< " " << endl;
cout << setw(15) << "State:" << state_<< " " << endl;
cout << setw(15) << "Zip:" << zip_<< " " << endl;
cout << setw(15) << "Date_Birth:" << dob_<< " " << endl;
cout << setw(15) << "Date_Death:" << dod_<< " " << endl;
cout << setw(15) << "Date_Wedding:" << dow_<< " " << endl;
cout << setw(15) << "Spouse:" << (spouse_ ? spouse_->GetFirstName() : "") << " " << (spouse_ ? spouse_-> GetLastName() : "") << endl;
for(unsigned int i = 0; i < children_.size(); i++)
{
cout << setw(15) << "Child: " << i << ": " << children_[i]->GetFirstName()<< " " << children_[i]->GetLastName()<< endl;
}
}
private:
std::string firstName_;
std::string lastName_;
std::string city_ ;
std::string state_ ;
std::string zip_ ;
std::string dob_ ;
std::string dow_;
std::string dod_;
std::string address_;
std::string spouseTempString;
std::vector<AddressNode*> children_;
AddressNode* spouse_;
unsigned int id_;
void AddressNode::AddChild(AddressNode& child)
{
vector<AddressNode*>::iterator iter;
if((iter = find(children_.begin(), children_.end(), &child)) != children_.end())
return;
children_.push_back(&child);
if (spouse_)
spouse_->AddChild(child);
}
public:
AddressNode(const std::string& firstName, const std::string& lastName, int id)
: children_(), id_(id)
{
firstName_= "";
firstName_+= firstName;
lastName_="";
lastName_+= lastName;
}
这里没有足够的代码来说明,但通过引用传递对象然后存储其地址总是很可疑
如果一个堆栈对象被传递给那个函数,你会得到各种奇怪的结果。
由于您的错误只发生在指针对象上,我更倾向于认为您在某个地方存在内存管理问题。
如果您真的想存储指针,首先传递指针,还是传递常量引用并存储副本?