I'm currently trying to refresh and improve my C++ skills and I'm reading a few books in parallel depending on the subject I need to dig into.
I'm currently spending time on The C++ Programming Language from Stroustrup. At page 61/62, there's an example of class for Complex numbers. It overloads a number of operators like += and -=. At the same time, it says that "Many useful operations do not require direct access to the representation of complex, so they can be defined separately from the class definition".
Now, when I try the following code:
#pragma once
#include <iostream>
class Complex
{
private:
double re, im;
public:
Complex(double r, double i): re{r}, im{i} {}
Complex(double r): re{r}, im{0} {}
Complex(): re{0}, im{0} {}
double real() const { return re; }
void real(double d) { re = d; };
double imag() const { return im; }
void imag(double d) { im = d; }
void print();
Complex& operator+= (Complex z) { re += z.re, im += z.im; return *this; }
Complex& operator-= (Complex z) { re -= z.re, im -= z.im; return *this; }
};
Complex operator+ (Complex a, Complex b) { return a += b; }
I get a link error: class Complex_cdecl operator+(class Complex, class Complex) already defined in Complex.obj
One or more multiply defined symbols found.
So, I suppose the code presented in the book here is only partial. I can't figure out though what's the right way to overload both + and +=. Is the book wrong here or obsolete?
Thanks for your help.