Okay, so the code below is a copy of code from an online course thingy I'm attempting, and is meant to be demonstrating overloading an operator. In this case it's the + operator. However, I'm having difficulty following how it works.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
#include <iostream>
using namespace std;
class V {
public:
float vec[2];
V(float a0, float a1) { vec[0]=a0; vec[1]=a1; } // constructor
V operator+(V &arg) { // overloaded operator
V res(0.0f,0.0f);
for(int i = 0; i < 2; i++)
res.vec[i] = vec[i] + arg.vec[i]; // <-- don't quite get this
return res;
}
};
int main(void) {
V v1(0.0f, 1.0f);
V v2(1.0f, 0.0f);
V v3(0.0f, 0.0f);
v3 = v1 + v2;
cout << "(" << v3.vec[0] << ", " << v3.vec[1] << ")" << endl;
return 0;
}
|
So, I get the gist of the code, but I don't quite see how the line
res.vec[i] = vec[i] + arg.vec[i];
does its stuff.
I can see that res.vec[i] is being assigned the result of
vec[i] + arg.vec[i];
, and the result is returned in res, but I don't get how the code figures out anything about vec[i] or arg.vec[i], since these are not passed, per se, to the overload function (i.e. as they would be in a normal function).
Nonetheless, I see there is a single parameter for the function, but nothing appears to be passed in the
v3 = v1 + v2;
line.
If someone could relieve me of my ignorance on this example, or in general with overloaded operators, then it would be much appreciated. Thanks!