我很难绕过指针。我可以想象这里有人可以更直观地概念化复制构造函数。我知道您不能简单地将指针分配给彼此(浅拷贝),但我在实际复制对象时遇到了困难。
这是我的代码示例:
class LList {
/* stuff */
private:
struct node {
node *next;
node *prev;
int *o;
};
node *first; // The pointer to the first node (NULL if none)
node *last; // The pointer to the last node (NULL if none)
}
感谢您的帮助!
最佳答案
当你为包含动态分配的T* p<的对象
(在你的情况下可能是 X
编写复制构造函数X(const T& other)
时Node*
),你最终可能会写这样一行:
p = new T(*other.p);
这会创建您正在复制的对象所指向的对象的拷贝,从而为您提供该对象的深层拷贝。在您的情况下,这将最终导致列表的递归深度复制。
关于c++ - 如何在双向链表上执行深拷贝?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13668252/