0

I am writing a Complex class for an assignment in which one of the methods should overload the default addition operator when adding a double to the complex number. So far, I have the following code which correctly works for c+5 where c is some Complex object

Complex& Complex::operator+(const double& d) const
{
    return Complex(real + d, imag);
}

However, it doesn't like it when I do 5+c. I think it might be because of a prefix post-fix thing but I am not sure.

My question is if there is a way to also overload the + operator so that I can do something like 5+c. I tried searching for a solution online but the only answers I could find dealt with the increment/decrement operators where you just add an int argument for the post-fix. I tried the same thing for + but it doesn't work.

Thank you very much.

sshashank124
  • 31,495
  • 9
  • 67
  • 76

1 Answers1

2

Two options come to mind:

1) Implement two non member functions:

Complex operator+(const Complex& lhs, double rhs);
Complex operator+(double lhs, const Complex& rhs);

2) Make Complex implicitly constructable from double (if it isn't already), and implement a single non-menber:

Complex operator+(const Complex& lhs, const Complex& rhs);
juanchopanza
  • 223,364
  • 34
  • 402
  • 480