可视化 如何实现 c++ 列表的运算符=?

visual How to implement c++ list's operator=?

本文关键字:列表 运算符 c++ 何实现 实现 可视化      更新时间:2023-10-16

这是一个关于实现c++列表的任务,所以如果有人问"为什么不使用[非常方便的东西]而不是列表",答案是问我的教授,而不是我。我也不能更改我的标题。请注意,此版本的列表只需要能够接受int数据类型。假设我已经实现了列表的所有其他功能。

首先,我尝试过这个方法,但没有成功,因为我意识到我不能迭代l,它是常数(所以没有l.curr=l.curr->next等(。

Linkedlist& Linkedlist::operator=(const Linkedlist& l)
{
if (this != &l)
{
this->clear();
l.curr = l.head;
for (int i = 0; i < l.numElem; i++)
{
this->push_back(l.curr->data);
}
}
return *this;
}

我也试过这个,但再一次我不能以任何方式修改l的形状或形式,因为它是恒定的。类型限定符不兼容。

Linkedlist& Linkedlist::operator=(const Linkedlist& l)
{
if (this != &l)
{
this->clear();
for (int i = 0; i < l.numElem; i++)
{
this->push_back(l.front());
l.pop_front();
}
}
return *this;
}

抱歉/如果我需要提供更多信息,请告诉我。

我无法迭代l,它是常量(因此没有l.curr = l.curr->next等(。

这不是迭代对象节点的方式。您可以使用:

for (auto iter = l.head; iter != nullptr; iter = iter->next )
{
}

在您的情况下,您可以使用:

Linkedlist& Linkedlist::operator=(const Linkedlist& l)
{
if (this != &l)
{
this->clear();
for (auto iter = l.head; iter != nullptr; iter = iter->next )
{
this->push_back(iter->data);
}
}
return *this;
}