gpt4 book ai didi

c++ - 这个复制构造函数是否创建了输入对象的相同且独立的深层拷贝?

转载 作者:行者123 更新时间:2023-11-28 06:40:43 24 4
gpt4 key购买 nike

我为 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;
}
}

这是添加方法:

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++;
}
}

最佳答案

Polynomial::add() 创建一个新节点并将其插入到链表中。

您的复制构造函数遍历现有链表以将注释添加到正在构造的列表中。

所以是深拷贝而不是浅拷贝。

备注:

在开始添加节点之前,请考虑在复制构造函数中将显式 headtail 初始化为 NULL

根据 Node 构造函数,显然使用 coeffdegree 您可能会考虑不要将这些值冗余地重新分配给 temp 成员。

nDegree--; 在你的循环中的目的对我来说并不完全清楚。我想你可以放弃它。

关于c++ - 这个复制构造函数是否创建了输入对象的相同且独立的深层拷贝?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26026984/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com