首页 > 解决方案 > 如何实现 C++ 列表的 operator=?

问题描述

这是一个关于实现 c++ 列表的任务,所以如果有人要问“你为什么不使用 [非常方便的东西] 而不是列表”,答案是问我的教授,而不是我。我也不能改变我的标题。请注意,此版本的 list 只需能够接受 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;
}

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

标签: c++visual-c++

解决方案


我无法迭代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;
}

推荐阅读