I'm currently creating a class for complex numbers, and so I figured to make it easier, I'd allow for operations such as a = b + c, instead of a = b.add(c). For example, here is my implementation of addition of two complex numbers:
// An addition operator for the complex numbers
Complex Complex::operator + (Complex n) {
return Complex(this->real + n.real, this->imaginary + n.imaginary);
}
In this example, adding complex numbers a + b would have the same result as adding b + a, as they should.
However, the issue comes when dealing with non-commutative operators and integers. For example, division by an integer or division of an integer. How could I make it such that both:
a = complex / integer
and
a = integer / complex
give correct responses?
In other words, how can I overload operators in two ways?
If you write your operator as a free function, rather than a class member, you can specify both operands.
Complex operator/ (int lhs, Complex rhs);
Complex operator/ (Complex lhs, int rhs);
You might have to make them a friend function, if you need to access private members.
(I'll leave it to you to decide whether you need int, or float, or whatever at the front.)
EDIT: A bit fuller example might be:
Complex operator/ (int lhs, Complex rhs) {
Complex answer;
double mag = rhs.real*rhs.real+rhs.imag*rhs.imag;
answer.real = lhs*rhs.real/mag;
answer.imag = -lhs*rhs.imag/mag;
return answer;
}
and then a bit later:
f = 6/f;
(again I'm assuming public member variables for ease of use).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With