操作员 左右超载

operator+ overload left and right

本文关键字:超载 左右 操作员      更新时间:2023-10-16

我想超载操作员 在两边工作。当我使用操作员 时,我想将元素推入类的向量。这里是我的代码:

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+表示复制。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;
}

操作员 应返回副本

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