简体   繁体   English

如何将 + 和 += 运算符重载为非成员函数?

[英]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.我目前正在尝试更新和提高我的 C++ 技能,并且根据我需要深入研究的主题,我正在同时阅读几本书。

I'm currently spending time on The C++ Programming Language from Stroustrup.我目前正在研究 Stroustrup 的 C++ 编程语言。 At page 61/62, there's an example of class for Complex numbers.在第 61/62 页,有一个用于复数的 class 示例。 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".同时,它说“许多有用的操作不需要直接访问复数的表示,因此可以将它们与 class 定义分开定义”。

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.我收到一个链接错误: class Complex_cdecl operator+(class Complex, class Complex)已经在Complex.obj中定义 找到一个或多个多重定义的符号。

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 += .我不知道什么是overload ++=的正确方法。 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.在您的示例中, operator +应该inline ,以便 linker 知道多个 obj 文件可以包含相同的 function 定义。

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

Or the header file should contain only the declaration或者 header 文件应该只包含声明

Complex operator+ (Complex a, Complex b);

and exactly one cpp file should contain the definition并且只有一个 cpp 文件应该包含定义

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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