Hello! I've been working through the tutorial in the documentation section and I'm having some trouble wrapping my head around the overloading operator part.
the code:
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 29 30 31 32
|
// 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;
}
| |
And my take on what happens:
CVector() {}; is a constructor function (called by c, param and temp when they are created)
CVector (int,int); is a constructor function (called by a and b when they are created)
CVector operator + (CVector); is an operator function of type CVector that returns a CVector, this function gets called at the + symbol in the line c = a + b;
c = a + b; can be read as c = a.operator+ (b);
so at a + b; the object a calls it's operator+ function and the object b is filled in as the parameter. in the function operator+ two new objects are made, param and temp.
a.x = 3 (defined in the main) param.x = 1 (takes the value from b.x) and temp.x = 0
the line temp.x = x + param.x; can be read like this: the integer x from the object temp is equal to the integer x from the object a added to the integer x from the object param.
is the above really what happens?
When I was searching for more information on overloading operators I found the following code:
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 29 30 31 32 33
|
#include <iostream>
using namespace std;
class complx
{
double real,
imag;
public:
complx( double real = 0., double imag = 0.); // constructor
complx operator+(const complx&) const; // operator+()
};
// define constructor
complx::complx( double r, double i )
{
real = r; imag = i;
}
// define overloaded + (plus) operator
complx complx::operator+ (const complx& c) const
{
complx result;
result.real = (this->real + c.real);
result.imag = (this->imag + c.imag);
return result;
}
int main()
{
complx x(4,4);
complx y(6,6);
complx z = x + y; // calls complx::operator+()
}
| |
I do not understand the way they created the operator+ function.
in this line:
complx operator+(const complx&) const;
it says complx& instead of just complx. Why do they do this? (it still works even when I remove the &)
They also say it is a const complx&, why exactly do they do this?
And the last part I dont get: they put another const at the end of the function before the semicolon. Why is this?
Any help would be very much appreciated!