【问题标题】:Add to list with operator overloading使用运算符重载添加到列表
【发布时间】:2016-11-01 20:19:26
【问题描述】:

建议我有以下课程:

class ListWrapper

{

     private: vector<MyItem> items;

     public : MyItem& operator+(MyItem& itm){items.push_back(itm);}

};

class MyItem
{
    private: int data;
};

是否可以使用带有 + 运算符的运算符重载将项目添加到 MyList?

即:

MyItem item1,item2,item3;
ListWrapper lw;

lw + item1 + item2+ item3;

我可以在 ListWrapper 上使用运算符,但是有没有办法像这个例子一样通过多个项目来拥有它?

【问题讨论】:

  • 从你的+ 运营商那里返回一些东西。它应该是ListWrapper

标签: c++ vector operator-overloading


【解决方案1】:

我建议不要使用带有副作用的 operator+,因为它会造成混淆。

更好:

ListWrapper& operator+=(std::initializer_list<MyItem> l) {
    items.insert(items.end(), l);
    return *this;
}

那么你可以这样做:

lw += {item1, item2, item3};

【讨论】:

  • 副作用是什么意思
  • @user3150947 修改对象是副作用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-17
  • 1970-01-01
  • 2019-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多