简体   繁体   English

左右运算符+重载

[英]operator+ overload left and right

i want to overload operator+ to work on both side.When i use operator+ i want to push the element into a vector of the class .Here is my code: 我想重载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;
}

operator+ implies a copy. operator+表示副本。 operator+= implies an in-place mutation. operator+=表示就地突变。

this is probably more idiomatic: 这可能更惯用:

#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;
}

operator+ should return a copy 运算符+应该返回副本

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM