c++ - 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不好:)
解决方案
如果您operator+=
为您的班级定义,请在您的班级实例上调用它:
yourlist += somedata;
将等于调用任何其他方法:
yourlist.operator+=( somedata );
它只是一个语法糖。所以你可以看到这与任何其他成员函数几乎相同(除了它允许你以特殊的方式调用它)。因此operator+=
,通过调用方法来实现addToList()
或反之亦然是非常好的。
推荐阅读
- wpf - wpf TreeView 绑定具有多个 TreeViewItemStyle
- javascript - 未捕获的 SyntaxError:意外的保留字(等待)
- javascript - 即使在成功的 API 调用之后,Ember 也不会填充模型
- reactjs - 更改主题时性能缓慢
- sparql - SPARQL wikidata group-by:获取答案中的分组项目(具有多个城市的河流)
- java - Spring 框架 Java
- android - 将 Meteor Cordova 构建的应用程序连接到本地服务器和数据库
- mqtt - Mosquitto MQTT 代理的远程管理 API
- date - 将日期列从对象转换为日期格式
- ios - 使用 swift 进行本地化时停止翻转条形按钮项目