簡體   English   中英

左右運算符+重載

[英]operator+ overload left and right

我想重載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+表示副本。 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;

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM