在使用链表时,我在实现深拷贝时遇到了很多麻烦。我很确定问题是使用 otherList.listData-> 给我一个指向原始列表中数据的指针,而不是复制值。但是,我对如何直接访问该数据感到困惑。我在想你可以取消引用那些指针,但我一定是用错了语法。对于我需要的 CourseList 类数据,也没有获取/设置方法。
有没有人有什么想法???
头文件
class CourseList
{
private:
struct CourseNode
{
int CRN;
char letterGrade;
CourseNode *next;
};
int length;
CourseNode *listData;
public:
CourseList();
CourseList(const CourseList& otherList);
~CourseList();
};
CPP文件
CourseList::CourseList(const CourseList& otherList)
{
length = otherList.length;
for (int i = 0; i < length; i++)
{
CourseNode* temp = new CourseNode;
temp->CRN = otherList.listData->CRN;
temp->letterGrade = otherList.listData->letterGrade;
temp->next = otherList.listData->next;
listData = temp;
}
}
最佳答案
您的复制构造函数已损坏:它最终将最后一个元素分配给 listData
而不是第一个元素。这意味着您泄漏了列表中除最后一个元素之外的所有元素。此外,每次您创建一个 new CourseNode
时,您都将其 next
指针分配给了完全相同的东西——对于所有复制的元素!
关于c++ - 使用链接列表复制 Ctor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26502966/