简体   繁体   中英

how to overload + and += operators as non-member functions?

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.

In your example the operator + should either be made inline so that the linker knows that multiple obj files can contain the same function definition.

inline Complex operator+ (Complex a, Complex b) { return a += b; }

Or the header file should contain only the declaration

Complex operator+ (Complex a, Complex b);

and exactly one cpp file should contain the definition

Complex operator+ (Complex a, Complex b) { return a += b; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM