【发布时间】:2017-11-29 00:53:40
【问题描述】:
我不允许使用 STL 容器!
以下代码中的SortedListClass(const SortedListClass< T > &rhs)、operator=(const SortedListClass< T > &rhs) 和clear() 函数出现分段错误。
这是调试器的结果:
#0 __GI___libc_free (mem=0x4) at malloc.c:2929 #1 0x00000000004016d6 在 SortedListClass::clear (this=0x7ffffffde470) at SortedListClass.inl:45 #2 0x00000000004011b5 在 SortedListClass::operator= (this=0x7ffffffde470, rhs=...) at SortedListClass.inl:28 #3 0x0000000000400c88 in main () at project5.cpp:33SortedListClass.inl 第 45 行如下:delete tempHead;
SortedListClass.inl 第 28 行如下:this->clear();
project5.cpp 第 33 行如下:copyTestList = testList;
代码如下:
SortedListClass.inl
template<class T>
SortedListClass< T >::SortedListClass()
{
head = NULL;
tail = NULL;
cout<<"Empty list intialized...."<<endl;
}
template<class T>
SortedListClass< T >::SortedListClass(const SortedListClass< T > &rhs)
{
cout<<"Copied Value(s)"<<endl;
LinkedNodeClass< T > *rhsFront;
LinkedNodeClass< T > *newCopyNode;
rhsFront = rhs.head;
while(rhsFront != NULL)
{
newCopyNode = new LinkedNodeClass< T >(rhsFront,rhsFront->getValue(),
rhsFront->getNext());
rhsFront = newCopyNode;
rhsFront = rhsFront->getNext();
}
}
template<class T>
void SortedListClass< T >::operator=(const SortedListClass< T > &rhs)
{
this->clear();
*this = SortedListClass(rhs);
}
template<class T>
void SortedListClass< T >::clear()
{
LinkedNodeClass< T >*tempHead;
LinkedNodeClass< T >*tempTail;
tempHead = head;
tempTail = tail;
while(tempHead != NULL || tempTail != NULL)
{
cout << "Deleting node(s) --> "<< endl;
tempHead = head;
delete tempHead;
tempHead = NULL;
head = tempHead;
tempTail = tail;
delete tempTail;
tempTail = NULL;
tail = tempTail;
}
cout<<"Deleting complete"<<endl;
}
project5.cpp
int main()
{
SortedListClass< int >testList;
testList.insertValue(3);
testList.printForward();
testList.insertValue(4);
testList.printForward();
int theVal = 0;
SortedListClass<int>copyTestList(testList);
copyTestList = testList;
copyTestList.getNumElems();
int index = 0;
int outval = 0;
copyTestList.getElemAtIndex(index,outval);
copyTestList.printForward();
copyTestList.removeLast(theVal);
copyTestList.printBackward();
return 0 ;
}
【问题讨论】:
-
显示的代码不符合stackoverflow.com对minimal reproducible example的要求,因此无法给出权威答案;所以一般的答案“分段错误是因为你的代码中某处的错误”将适用。尽管如此,默认构造函数似乎初始化了一些名为
head和tail的类成员,在复制构造函数中找不到它们。这似乎是非常非常错误的。然后,在 clear():tempHead = NULL; head = tempHead;似乎也很错误。这里有太多明显的基本问题。 -
你的
clear函数完全没有意义。在while循环的第一次迭代结束时,head和tail都设置为NULL。那么它怎么会循环呢?我同意 Sam 的评论,“这里有太多明显的基本问题。”你只需要找到/修复所有的错误,也许这个项目太雄心勃勃了你的技能水平。 -
复制构造函数没有初始化
head和tail成员,while()循环看起来全错了。而operator=看起来会导致无限递归循环。 -
无关:
template<class T> void SortedListClass< T >::operator=(const SortedListClass< T > &rhs) { this->clear(); *this = SortedListClass(rhs); }是末日镇。*this = SortedListClass(rhs);将导致无限递归。阅读 stackoverflow.com/questions/3279543/… 以获得更好的路径。 -
head和tail的类型是什么?这是否能够在不声明类型的情况下编译?
标签: c++ linked-list operator-overloading