首页 > 解决方案 > C++中链表的重载运算符+=

问题描述

我有一个重载运算符 += 的分配,因此它将新数据添加到列表中。List += data 因此应该意味着 list=list+data,这在逻辑上类似于 operator += 对 int 等基本类型所做的事情。我很讨厌链表,我刚刚想出了如何用函数来做到这一点,所以我不知道在这种情况下该怎么做。

List& List::operator+=(const T& newData)
    {
        last_ = (!first_ ? first_ : last_->next_) = new Elem(newData);
        ++listSize_;
        return *this;
    };

where T is from template <typenameT> class List {...} "

可以吗,我的意思是我可以使用函数中的代码吗

List& addToList (const T& newData) {same code snippet}

,它会给我预期的结果吗?我不这么认为,因为它从不在代码中使用运算符本身,这让我有点困惑。

很明显我是编码的初学者,很抱歉我的cpp不好:)

标签: c++linked-listoverloadingaddoperator-keyword

解决方案


如果您operator+=为您的班级定义,请在您的班级实例上调用它:

yourlist += somedata;

将等于调用任何其他方法:

yourlist.operator+=( somedata );

它只是一个语法糖。所以你可以看到这与任何其他成员函数几乎相同(除了它允许你以特殊的方式调用它)。因此operator+=,通过调用方法来实现addToList()或反之亦然是非常好的。


推荐阅读