所以我真的很沮丧为什么会这样。我正在实现一个类似于 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;
}