【发布时间】:2013-10-14 04:42:11
【问题描述】:
我真的很困惑为什么这个复制构造函数不起作用!我正在创建一个iter 指针,它指向与head 相同的ListNode,但是当我将内容从s 复制到it 时,head 和iter 没有连接!
换句话说,当打印头时,只有第一个字符在那里,但如果我要遍历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是内置类型吗?因为它似乎没有在任何地方初始化。 -
Sorry yes NumAllocations 是 Mystring.h 中定义的全局变量
标签: c++ pointers memory-management linked-list copy-constructor