I'm learning C++ and I created two simple hello-world applications. In both of them I use operator overload, but here is the problem. On the first one, I can provide two arguments to overload operator, and it's fine.
Header:
enum Element {a,b,c,d,e};
Element operator + (Element x, Element y);
//more overloads for -, *, / here
Source:
Element operator + (Element x, Element y) {
return ArrayOfElements[x][y];
}
But in my second app (simple complex number calculator) - this method didn't work. After googling and figuring out why, I end up with this code:
Header:
struct Complex {
double Re;
double Im;
Complex (double R, double I) : Re(R), Im(I) { }
Complex operator + (Complex &Number);
//more overloads
};
Source:
Complex Complex::operator + (Complex &Number)
{
Complex tmp = Complex(0, 0);
tmp.Re = Re + Number.Re;
tmp.Im = Im + Number.Im;
return tmp;
}
It's working now, but I want to know, why in the first piece of code I was allowed to put two arguments in operator overloading, but with the second one I was given the following error?
complex.cpp:5:51: error: 'Complex Complex::operator+(Complex, Complex)' must take either zero or one argument
It's the same whenever I use classes or not. I've been seeking through many docs and the second way seem to be more correct. Maybe it's because of different argument types?
Both sources compiled with -Wall -pedantic parameters using g++, both are using the same libraries.
Aucun commentaire:
Enregistrer un commentaire