我为Polynomial类创建了以下复制构造函数。构造函数应该创建输入Polynomial对象的独立深层副本。复制构造函数实际上是这样做还是创建浅拷贝?
Polynomial::Polynomial(const Polynomial &p) {
cout << "Enter method\n";
if(p.head != NULL) {
cout << "Enter if\n";
Node* n = p.head;
int nDegree = n->degree;
while(n != NULL) {
this->add(n->coeff, n->degree);
nDegree--;
n = n->next;
}
n = NULL;
}
}
这是add方法:
void Polynomial::add(const float& coeff, const int& degree) {
Node *temp = new Node(coeff, degree, NULL, NULL);
temp->coeff = coeff;
temp->degree = degree;
if(tail == NULL) {
head = temp;
tail = temp;
arrSize++;
}
else {
temp->prev = tail;
tail->next = temp;
tail = temp;
arrSize++;
}
}
答案 0 :(得分:1)
Polynomial::add()
创建一个新节点并将其插入链接列表中。
您的复制构造函数遍历现有链接列表,以便向正在使用的列表添加注释。
所以这是一个深层拷贝而不是浅拷贝。
<强>说明:强>
在开始添加节点之前,请考虑在复制构造函数中初始化explicitey head
和tail
到NULL
。
根据Node
构造函数,显然使用coeff
和degree
,您可以考虑不要将这些值重新分配给temp
成员。
我的循环中nDegree--;
的目的并不完全清楚。我想你可以放弃它。