Can somebody explain me what is being done in the CVector CVector::operator+ (CVector param). How does the dot operator work with temp. I understand when you do object.function() but how does it make sense to do object.object does this just set them both equal to each other? Confused!!
#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;
}
This is called operator overloading. What it is doing in this case is allowing you to add two of CVector objects together, as shown in the
mainfunction.When
a + boccurs in the main function, theoperator+method of theaobject is called, withbas theparam. It thus constructs atempobject that combines the coordinates of the two, and returns it.ETA: Rereading your question, I think you might also be asking what the line
means. Note that C++ objects don’t just have functions they can call (like
object.function()), they have members, which are themselves variables that can be accessed and changed. In this case,xandyare ints that belong to theCVectorclass. Read this tutorial closely.