Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overload both possibilities of non-commutative operators in C++?

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?

like image 641
Cisplatin Avatar asked Dec 27 '13 04:12

Cisplatin


1 Answers

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).

like image 121
tabstop Avatar answered Sep 19 '22 20:09

tabstop