Please help!! I need to overload the + operator for the following class:
class complex {
double real;
double imag:
...
};
How do I do this??
Printable View
Please help!! I need to overload the + operator for the following class:
class complex {
double real;
double imag:
...
};
How do I do this??
Overloading an operator is much like writing a function, except that the name of the function is operator+.
So think of what a + operator would take in and return. It would take in an object and return an object with altered values. Like this
object3 = object1 + object2;
So the operator function would start out like this:
Usually with an overloaded operator+ you want to have an overloaded operator=. Just go through the same steps.Code:class Complex {
double real;
double imag:
...
};
Complex Complex::operator+(Complex &argObject)
{
Complex tempObject; // Create temp object to return
tempObject.real = this->real + argObject.real;
tempObject.imag = this->imag + argObject.imag;
// etc.. etc..
return tempObject;
}
Good luck
So, can I do:
Complex complex :: operator+(Complex &argObject)
{
Complex tempObject;
tempObject.real = real + argObject.real;
tempObject.imag = imag + argObject.imag;
return tempObject;
}
I'm not at a computer with compiler so I don't know if this will work.
Thanks for your help!!
As long as you capitalize the 1st letter in the 2nd complex on the 1st line. Wow, that sounded weird. :D
Thanks!! I appreciate it!!
yup that should work too. Using the this-> syntax just states explicitly where real and imag are coming from. The object on the left hand side of the operator is generally considered to be the calling object and the object on the right hand side of the operator is generally considered the called object, to replace something like this:
class Complex
{
//
public:some code
Complex add(Complex & rhs);
//more code
};
and calling it like this:
int main()
{
Complex first, second, third;
third = first.add(second);
}
instead of
third = first + second;
Overloaded operators only make the programmers live easier, they don't really add functionality. That also means that the above overloaded + operator will only work with two objects of type Complex. What happens if you want to do this:
int fourth;
Complex first, second, third;
third = first + fourth;
or how about this:
third = fourtn + second;
Each different scenario needs it's own overloaded + operator. So in a robust class you often end up with a series of overloaded + operators, and whatever other math operators you wish to have available for your class.
Wow, Elad. Thanks!! I struggle with this stuff as you can probably tell from my questions. You've taken me a step further in understanding. I appreciate it.
Elad, you forgot one of the main reasons C++ has operator overloading, templates. It makes life so much easier when using them.