Classes 2 problem...

Hello I am reading the tutorial to try and learn c++ by myself. Today I move on to Classes II.

This is program
// vectors: overloading operators example
#include <iostream>
using namespace 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;
}



I do not understand:
CVector CVector::operator+ (CVector param) {
CVector temp;
temp.x = x + param.x;
temp.y = y + param.y;
return (temp);
}


How can you add thing with ONE parameter? It doesn't make sense!
I don't completly understand your question, but if it is about the .x and .y:

Both temp and param are of class CVector, wich seems to have (at least) to membervariables: x and y. So one object (param) can have several values in it. By writing param.x you access the x-variable of param, by writing param.y you access the y-variable of param.

Hope this helps. If this isn't an answer to your question: what are you asking exactly?
Last edited on
To me it seems like the parameter of the operator+ function is a single new CVector class called param. Then he makes a new Cvector class called temp. Then he says that temp.x is equivilant to x (where is this defined) + param.x (I think this is retained by the input of a Cvector class)...

Does the operator+ funtion work by taking the first CVector and getting the "x" and "y" values from there and then reading param.x and param.y from the second CVector class (the parameter)???
Last edited on
x and y are membervariables. Take a look at this:

1
2
3
4
5
6
7
8
9
10
//...class declaration...

CVector firstObject;
CVector secondObject;
firstObject.x=1;
firstObject.y=2;
secondObject.x=3;
secondObject.y=4;
CVector thirdObject;
thirdObject=firstObject+secondObject;


Here the operator+ function from firstObject is called. As parameter, secondObject is used. It returns an object (temp) that has the added values from x (member of firstObject) + param.x (member of parameter) end y+param.y (same here) in it. This returnvalue is stored into thirdObject.
Last edited on
Topic archived. No new replies allowed.