I'm creating a complex
struct which overloads operators +,*,-,...etc. I've written the following code:
struct complex{
double re;
double im;
complex& operator+(const complex& c){
return complex{this->re + c.re, this->im + c.im};
}
complex& operator+(const double d){
return complex{this->re + d, this->im};
}
// operator overload for double + complex?
complex& operator*(const complex& c){
complex cx;
cx.re = this->re*c.re - this->im*c.im;
cx.im = this->re*c.im + this->im*c.re;
return cx;
}
};
Which gives me a couple issues:
- The first two methods (both) give me
object has an uninitialized const or reference member
andinitial value of reference to non-const must be an lvalue
errors. I assume this is because I've initialized thecomplex
object and am returning it in the same statement, and it expects a reference, but I'm not returning an lvalue. Is this correct? - There are three scenarios in which I'd be adding:
complex + complex
,complex + double
, anddouble + complex
. How would I write the method for adouble + complex
when the first element is not of typecomplex
? - Considering I plan on overloading multiple operators, must I overload them for all three cases (i.e. for multiplication,
complex * complex
,complex *the double
, anddouble * complex
)? This seems like a lot of unnecessary code, is there a better way to implement this?