Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operators defined only one way - C++

I've created a class of complex numbers, defined operations and some functions like arg, modulus etc. I've also defined the imaginary unit i as constant in a namespace. The problem is that z = i + 2 doesn't return any error and work correctly but the compiler doesn't accept the line z = 2 + i saying that the operand is invalid between int and const complex.

What should I do to get the operation defined both ways?

like image 453
Moray Avatar asked Mar 04 '26 20:03

Moray


2 Answers

You should implement either a conversion between integer and complex number or define both operators:

complex operator+(int a, const complex& b)

and

complex operator+(const complex& a, int b)
like image 107
Ivaylo Strandjev Avatar answered Mar 07 '26 09:03

Ivaylo Strandjev


You should overload complex operator+(int lhs, const complex& rhs); for your class. Make this a friend function so you pass in both parameters.

like image 25
Tony The Lion Avatar answered Mar 07 '26 09:03

Tony The Lion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!