【发布时间】:2013-10-18 04:10:19
【问题描述】:
所以我对为什么会发生这种情况感到非常沮丧。我正在实现一个类似于 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);
}
静态公共函数
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;
}
【问题讨论】:
-
类定义将很好地帮助这项工作。节点管理代码更是如此。我看到了为什么
dest甚至提供 给命名不佳的strcpy成员的零原因。它是按值传递的,无论它是什么都立即在第一行丢失,所以它也可能是一个局部变量而不是一个参数。该功能看起来可能有问题,所以我将从那里开始。 -
我添加了类定义。 strcpy 是 std::string 的成员函数,并且此类要尽可能与该类相同,因此名称选择。就像我提到的列表已正确复制,因为当我在返回之前打印它时,它打印得很好,当我尝试在 operator = 方法的最后两行中使用该指针“head”创建一个新对象时它会搞砸。
标签: c++ pointers constructor linked-list