我已经在这个问题上好几天了,但我似乎无法找出为什么我的最后两件事无法打印出来。代码很长,所以我不会全部发布,但如果您需要,我愿意提供完整的源代码。
基本上,我在向每个列出的元素添加 1 个元素后调用打印函数。除了最后两个 Spouse 和 Child 之外,它将全部打印出来。这两个是最复杂的,因为它们也是它们自己的列表。当我为 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;
}
最佳答案
这里没有足够的代码来说明,但是通过引用传递一个对象然后存储它的地址总是可疑的。
如果将堆栈对象传递给该函数,您将得到各种奇怪的结果。
因为你的错误只发生在指针对象上,我更倾向于认为你在某处有内存管理问题。
如果你真的想存储一个指针,首先传递指针,还是传递一个常量引用并存储一个拷贝?
关于c++ - 为什么我的打印函数不会显示链表的任一子节点中的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33515539/