Hi all,
It's getting interesting now, but also more difficult. Please have a look at the following example for overloading operators in order to create a vector addition operation:
// vectors: overloading operators example
#include <iostream>
usingnamespace std;
class CVector {
public:
int x,y;
CVector () {};
CVector (int,int);
CVector operator + (CVector);
};
CVector::CVector (int a, int b) {
x = a;
y = b;
}
CVector CVector::operator+ (CVector param) {
CVector temp;
temp.x = x + param.x;
temp.y = y + param.y;
return (temp);
}
int main () {
CVector a (3,1);
CVector b (1,2);
CVector c;
c = a + b;
cout << c.x << "," << c.y;
return 0;
}
Can somebody give me a detailed explanation of lines 17 and 18? I have also some trouble with line 15, to be honest. I ran a debug version of the code and could follow the compiler steps quite good, but it eludes me what happens really in these lines (I mean where the variables from a, b are inserted etc., that sort of stuff).
In lines 16 a vector CVector temp is created. Then in lines 17 and 18 its members x and y are set to sum of values of x and y of the original object and of the object that is passed as argument to the operator-function.
So, all the effort is essentially to construct the part "+ param.x(y)"? which fulfils our wish for vector addition? If that's it, I may have understood now. But it also confirms I lack a certain talent for C++ ;).
Thank you for the illuminating explanations