1
我真的很困惑,为什么这个拷贝构造函数不工作!我正在创建一个指向与head
相同的ListNode的iter
指针,但是当我将s
中的内容复制到it
,head
和iter
未连接!链接列表复制构造函数C++
换句话说,当打印头时,只有第一个字符在那里,但如果我要遍历iter
,列表的其余部分就在那里。 为什么不是iter
和head
指向相同的对象?!
注意:这是一个链接列表被用来实现一个名为MyString的类。
struct ListNode {
char info;
ListNode *next;
ListNode() : info('0'), next(0) {}
ListNode (char c) : info (c), next(0) {}
};
class MyString {
private:
ListNode *head;
MyString::MyString(const MyString & s) {
if (s.head == 0)
head = 0;
else {
head = new ListNode (s.head -> info);
++NumAllocations;
ListNode *iter = head;
for (ListNode *ptr = s.head -> next; ptr != 0; ptr = ptr ->next) {
iter = iter -> next;
iter = new ListNode (ptr -> info);
++NumAllocations;
}
}
}
}
是内置类型的'NumAllocations'?因为它似乎没有在任何地方初始化。 – juanchopanza
对不起是NumAllocations是Mystring.h中定义的一个全局变量 – Tangleman