Say if i wanted to convert the following function to an overlaoded +=:

 ``123456789101112131415`` ``````void addvec(vector& v1, vector& v2) { if (v1.size() > v2.size()) v2.resize(v1.size()); else if (v2.size() > v1.size()) v1.resize(v1.size()); while (x < v1.size()) { v1.at(x) = v1.at(x) + v2.at(x); x++ }``````

Something tells me that you can't just do this

 ``1234567891011121314`` ``````operator+=(vector& v1, vector& v2) { if (v1.size() > v2.size()) v2.resize(v1.size()); else if (v2.size() > v1.size()) v1.resize(v1.size()); while (x < v1.size()) { v1.at(x) = v1.at(x) + v2.at(x); x++ }``````

but should do this:

 ``1234567891011121314151617`` ``````vector& operator+=(vector& v1, vector& v2) { if (v1.size() > v2.size()) v2.resize(v1.size()); else if (v2.size() > v1.size()) v1.resize(v1.size()); while (x < v1.size()) { v1.at(x) = v1.at(x) + v2.at(x); x++ } return v1; }``````

is that correct? My brain i triggering against the first because doesn't assignment have to return something in case of future assignment?
Last edited on
Well the first operator is obviously wrong since it has to have a return type. Your second is fine except that you should be taking the second parameter by const reference (you aren't modifying it).
Many thanks Zhuge
Might want to have a look at this line: `v1.resize(v1.size());`
And this: `v1.at(x) = v1.at(x) + v2.at(x);`
at() performs a range check, even though you just made sure that the index will always be valid.
Topic archived. No new replies allowed.