gpt4 book ai didi

c++ - 链表重载运算符 = 运行时错误

转载 作者:行者123 更新时间:2023-11-30 04:13:18 26 4
gpt4 key购买 nike

所以我真的很沮丧为什么会这样。我正在实现一个类似于 std::string 的类,但这是使用链接列表而不是数组。我的重载运算符 = 由于某些奇怪的原因无法正常工作。下面你可以看到,当我在方法中打印指针时,字符串被复制到链接列表,但是当我创建一个字符串对象并返回这个指针时,控制台打印出无限垃圾。对我在这里缺少的东西有什么想法吗? (我只是贴相关代码)

static int NumAllocations = 0;

struct ListNode {
char info;
ListNode *next;
ListNode () : info('0'), next(0) {}
ListNode ( char c ) : info (c), next(0) {}


};


class MyString {
private:
ListNode *head;
static void delstring (ListNode *l);
static int strlen (ListNode * head);
static ListNode* strcpy (ListNode *dest, ListNode *src);
public:

MyString::MyString () : head(0) {}

MyString::MyString (ListNode *l) : head(l) {}

MyString::MyString( const MyString & s ) {
if (s.head == 0)
head = 0;
else
head = strcpy(head, s.head);
}


MyString MyString::operator = (const MyString & s ){
ListNode *renew = NULL;
if (head != s.head) {
if (head != 0)
delstring(this -> head);

head = strcpy(head, s.head);
// printList(head); (this prints out the string just fine, so it must be the constructor ? but what about it ?!

MyString res (head);
return res;
}
}


MyString::~MyString(){
if (head == 0)
return;
ListNode *temp = NULL;
do {
temp = head -> next;
delete head;
-- NumAllocations;
head = temp;
} while (temp != 0);
}

静态公共(public)函数

ListNode* MyString::strcpy (ListNode *dest, ListNode *src){
dest = new ListNode (src -> info);
++ NumAllocations;
ListNode *iter = dest;
for (ListNode *ptr = src -> next; ptr != 0; ptr = ptr ->next){
iter -> next = new ListNode (ptr -> info);
iter = iter -> next;
++ NumAllocations;
}
return dest;
}


void MyString::delstring (ListNode *l){
if (l == 0)
return;
ListNode *temp = NULL;
do {
temp = l -> next;
delete []l;

-- NumAllocations;
l = temp;
} while (temp != 0);
l = 0;
}

最佳答案

您的赋值运算符有两个根本性错误。

  • 并非所有控制路径都返回值。
  • 您首先不需要临时最终拷贝。该函数应该返回一个引用,特别是*this

所以...

MyString& MyString::operator = (const MyString & s )
{
if (head != s.head)
{
if (head != 0)
delstring(this -> head);
head = strcpy(head, s.head);
}
return *this;
}

此外,我在这段代码中看到的所有内容都表明 ListNode 对象是单独分配并链接在一起的,但是在 delstring 成员中你这样做:

void MyString::delstring (ListNode *l)
{
if (l == 0)
return;
ListNode *temp = NULL;
do {
temp = l -> next;
delete []l; // <<==== vector delete of single allocated item

-- NumAllocations;
l = temp;
} while (temp != 0);
l = 0;
}

也许试试这个:

void MyString::delstring (ListNode *& l)
{
while (l)
{
ListNode *temp = l;
l = l->next;
delete temp;
--NumAllocations;
}
}

请注意,这采用指针引用而不是指针。一旦列表为空,它就会将调用者的指针设置为 nullptr(假设您在构造时正确终止了列表,看起来您确实这样做了)。

关于c++ - 链表重载运算符 = 运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19441432/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com