复制列表类的构造函数,而无需在实现中使用任何方法
Copy constructor for List class without using any methods in implementation
我正在为列表类编写复制构造函数,要求不使用任何其他方法。
类片段如下:
class List {
private:
struct Node {
NodeData *data;
Node *next;
};
Node *head;
};
要求是为此类编写复制构造函数,并且在实现中不使用任何其他方法,除非我们可以将copy构造函数用于nodedata class
我已经写了复制构造函数,如下所示:
list::list(const list &t){
Node* q;
q=new Node;
while (p!=NULL){
q->x= p->x;}
}
这不起作用,请帮助如何根据需要编写复制构造函数。
我不同意这是一个奇特的练习的评论者,实际上很有趣,可以尝试做到这一点。以下内容应该让您了解如何尝试:http://ideone.com/ddc7bn
class List {
private:
struct Node {
int data; // simplification
Node *next;
Node(int d) {
data = d;
next = NULL;
}
};
protected:
Node *head;
Node *tail;
public:
List(int d) : head(new Node(d)), tail(head) {}
void append(int d) {
Node* n = new Node(d);
tail->next = n;
tail = n;
}
List(const List& rhs) {
if (head) delete head;
head=new Node(rhs.head->data);
Node* lhsCurrent = head;
Node* rhsCurrent = rhs.head->next;
do {
lhsCurrent->next = new Node(rhsCurrent->data);
rhsCurrent = rhsCurrent->next;
lhsCurrent = lhsCurrent->next;
} while (rhsCurrent!=NULL);
tail = lhsCurrent;
}
};
int main() {
List first(5);
first.append(6);
List second(first);
return 0;
}
相关文章:
- 实现无开销push_back的最佳方法是什么
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 这是实现图形的坏方法吗
- 在 c++ 中实现嵌套循环的更短方法吗?
- 如何实现 Front() 方法以返回模板化双向链表C++的第一个元素?
- 如何在从抽象基派生的类中实现相同的方法?
- C++数组队列实现方法错误
- 有没有一种通用的方法来实现不变量
- 'using namespace'实现细节的便捷方法(仅标头库)?
- 使用非递归插入方法实现 AVL 树
- C ++类型特征:确保子类实现方法
- 实现基于数字值(正、负、零)的条件表达式的最佳方法
- 在C++上实现高斯赛德尔迭代方法
- C++方法实现:是否可以避免每次都键入类名?
- 如何知道C2259 VS 2017错误未实现哪种方法?
- C++强制在子类中实现方法,但具有不同的签名
- 避免在每个派生类中重新实现方法调用
- C :执行模板类型实现方法
- 在C++中实现方法时继承不起作用
- 还有更好的实现方法吗?