如何将 + 和 += 运算符重载为非成员函数?
how to overload + and += operators as non-member functions?
我目前正在尝试更新和提高我的 C++ 技能,并且我正在根据我需要深入研究的主题并行阅读几本书。
我目前正在学习 Stroustrup 的 The C++ Programming Language。在第 61/62 页,有一个 class 的复数示例。它重载了许多运算符,例如 += 和 -=。同时,它说 "Many useful operations do not require direct access to the representation of complex, so they can be defined separately from the class definition".
现在,当我尝试以下代码时:
#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; }
我收到 link 错误:class Complex_cdecl operator+(class Complex, class Complex)
已在 Complex.obj
中定义
找到一个或多个多次定义的符号。
所以,我想本书中提供的代码只是部分代码。我不知道 +
和 +=
overload
的正确方法是什么。这本书是错了还是过时了?
感谢您的帮助。
在您的示例中,operator +
应该设为 inline
以便链接器知道多个 obj 文件可以包含相同的函数定义。
inline Complex operator+ (Complex a, Complex b) { return a += b; }
或者头文件应该只包含声明
Complex operator+ (Complex a, Complex b);
并且只有一个 cpp 文件应该包含定义
Complex operator+ (Complex a, Complex b) { return a += b; }
我目前正在尝试更新和提高我的 C++ 技能,并且我正在根据我需要深入研究的主题并行阅读几本书。
我目前正在学习 Stroustrup 的 The C++ Programming Language。在第 61/62 页,有一个 class 的复数示例。它重载了许多运算符,例如 += 和 -=。同时,它说 "Many useful operations do not require direct access to the representation of complex, so they can be defined separately from the class definition".
现在,当我尝试以下代码时:
#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; }
我收到 link 错误:class Complex_cdecl operator+(class Complex, class Complex)
已在 Complex.obj
中定义
找到一个或多个多次定义的符号。
所以,我想本书中提供的代码只是部分代码。我不知道 +
和 +=
overload
的正确方法是什么。这本书是错了还是过时了?
感谢您的帮助。
在您的示例中,operator +
应该设为 inline
以便链接器知道多个 obj 文件可以包含相同的函数定义。
inline Complex operator+ (Complex a, Complex b) { return a += b; }
或者头文件应该只包含声明
Complex operator+ (Complex a, Complex b);
并且只有一个 cpp 文件应该包含定义
Complex operator+ (Complex a, Complex b) { return a += b; }