操作员+左右过载

时间:2016-06-16 21:29:08

标签: c++ stl operators

我想重载operator +来兼顾两边。当我使用operator +我想将元素推入类的向量。这是我的代码:

template<typename TElement>
class grades {
private:
   vector<TElement> v;
public:
   grades& operator+(const int& a) {
      v.push_back(a);
      return *this;
   }
   grades& operator=(const grades& g) {
      v = g.v;
      return *this;
   }
   friend grades& operator+(const int& a,const grades& g) {
      //here i get some errors if i put my code
       return *this;
   }
};
int main() {
   grades<int> myg;
   myg = 10 + myg; // this operation i want
   myg = myg + 9; //this work
   return 0;
}

2 个答案:

答案 0 :(得分:0)

operator+表示副本。 operator+=意味着就地突变。

这可能更具惯用性:

#include <vector>
using namespace std;

template<typename TElement>
class grades {
private:
   vector<TElement> v;
public:
  grades& operator+=(int a)
  {
    v.push_back(a);
  }
   // redundant
//   grades& operator=(const grades& g) {
//      v = g.v;
//      return *this;
//   }

   friend grades operator+(grades g, const int& a) {
      g += a;
      return g;
   }
   friend grades operator+(const int& a,grades g) {
     g.v.insert(g.v.begin(), a);
     return g;
   }
};
int main() {
   grades<int> myg;
   myg = 10 + myg; // this now works
   myg = myg + 9; //this work
   return 0;
}

答案 1 :(得分:0)

operator +应该返回一份副本

@JsonInclude(Include.NON_NULL)