我创建了一个执行多个功能的链接列表程序。我写了一个函数来销毁以“top”作为参数的列表。我最终在析构函数中使用了这个函数。我真的可以测试一下吗?
这是我缩短的Family.h:
#ifndef FAMILY_H
#define FAMILY_H
#include<string>
using namespace std;
#include "Child.h"
#include "Wife.h"
#include "Husband.h"
class Family
{
protected:
HusPtr top;
void Destroy(HusPtr& top); //I know in order to access this in the Main, I'd have to make
//this Public. But I'd have to create a local pointer named top.
//Because the local pointer points to nothing, I get a segmentation
//fault.
public:
Family();
Family(HusPtr& h);
Family(const Family& source);
~Family();
};
#endif
这是我的Family.cpp中的Destroy函数:
void Family::Destroy(HusPtr& top)
{
HusPtr curr = top;
WifePtr w = curr->myWife;
while(curr != NULL)
{
if(curr->myWife != NULL)
{
while(w->myChildren != NULL)
{
ChildPtr c = w->myChildren;
ChildPtr cNext = c->mySibling;
w->myChildren = cNext;
delete c;
}
curr->myWife = NULL;
delete w;
}
HusPtr next = curr;
curr = next->nextFamily;
delete next;
top = curr;
}
}
我的Main.cpp:
using namespace std;
#include "Family.h"
HusPtr top; //points to nothing.
int main()
{
Family F1;
F1.ProcessTransaction("transaction.txt");
F1.Destroy(top);// gives a segmentation fault...likely due to the fact that top points to nothing.
}
Wife.h:
#ifndef HUSBAND_H
#define HUSBAND_H
#include<string>
using namespace std;
#include "Person.h"
class Husband;
typedef Husband* HusPtr;
class Wife;
typedef Wife* WifePtr;
class Husband:public Person
{
friend class Wife;
friend class Family;
protected:
HusPtr nextFamily;
WifePtr myWife;
public:
Husband();
Husband(long hSSN, string hFirst, string hLast);
void Print() const;
};
#endif
Wife.h:
#ifndef WIFE_H
#define WIFE_H
#include<string>
using namespace std;
#include "Person.h"
#include "Child.h"
class Child;
typedef Child* ChildPtr;
class Wife:public Person
{
friend class Family;
protected:
ChildPtr myChildren;
public:
Wife();
Wife(long wSSN, string wFirst, string wLast);
void Print() const;
};
#endif
Child.h:
#ifndef CHILD_H
#define CHILD_H
#include<string>
using namespace std;
#include "Person.h"
class Child;
typedef Child* ChildPtr;
class Child:public Person
{
friend class Family;
protected:
ChildPtr mySibling;
public:
Child();
Child(long cSSN, string cFirst, string cLast);
void Print() const;
};
#endif
这不是此任务中所需的功能,但无论如何我决定实施它。一切都很好,应该可以工作,但我真的认为我收到的分段错误是因为我传递了一个在Main.cpp中创建的指针,它没有指向任何地方。我是对的吗?
答案 0 :(得分:1)
在删除w后的第二次迭代中,您不会再次分配它。但是你试着再次访问它的孩子。所以它会崩溃。
in while循环
第一次迭代 ... 删除w;
第二次迭代
W-&GT;儿童;程序将崩溃。