I am trying to add 2 vectors using overloaded +
operator. https://stackoverflow.com/a/4421719/9329547 answer shows
inline X operator+(X lhs, const X& rhs) { lhs += rhs; return lhs; }
My case is I want to pass 2 vectors to class, then a function will modify them and will add using another method and return it. Here is the code.
class VO
{
private:
const std::vector<double> &vec1;
const std::vector<double> &vec2;
public:
VO (const std::vector<double> &x, const std::vector<double> &y): vec1(x), vec2(y) {}
std::vector<double> operator + (const std::vector<double> &, const std::vector<double> &) {}
std::vector<double> foo(....)
{
//vectors vec1, vec 2 are modified here then want to add them
std::vector<double> v3 = vec1 + vec2;
return v3;
}
};
int main()
{
std::vector<double> a={1,2,3,4,5}, b={9,8,7,6,5},c;
VO obj(a,b);
c=obj.foo();
return 0;
}
In this case, I am not sure how can I use this
to add 2 vectors.
Edit:
I can create vectorAdd
method in the class, pass 2 vectors and get addition. But I want to use operator +
for that. Operator +
is overloaded in many scientific libraries to add vectors (arrays).
Edit 2:
If I use my original code, I get error error C2804 binary operator + has too many parameters
. I am trying to add 2 vectors such that if a={1,2,3,4,5}, b={9,8,7,6,5}
, then a+b = {1+9, 2+8, 3+7, 4+6, 5+5} = {10,10,10,10,10}