Question

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?

Was it helpful?

Solution

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

OTHER TIPS

When you overload an operator for a class, it looks like this: s1.operator+(s2). As you can see, it has an implicit argument, this. Therefore, it only takes one argument. In order to use the version that takes two arguments, they must be free functions. If you want these free functions to see the private variables of your object, you must make them a friend inside your class declaration.

class Object
{
friend Object& operator+(int something, Object& other);
};

// not a member function, don't qualify Object::
Object& operator+(int something, const Object& other)
{
return other.private_variable + something;
}

This is why for example when you overload operator<<, it must be a free function.

// Bad code
class Test
{
    std::ostream& operator<<(std::ostream& os, const Test& test);
};

std::ostream& Test::operator<<(std::ostream& os, const Test& test)
{
}

The implicit this is not an ostream object, and so you cannot chain calls this way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top