[英]how to overload + and += operators as non-member functions?
我目前正在嘗試更新和提高我的 C++ 技能,並且根據我需要深入研究的主題,我正在同時閱讀幾本書。
我目前正在研究 Stroustrup 的 C++ 編程語言。 在第 61/62 頁,有一個用於復數的 class 示例。 它重載了許多運算符,例如 += 和 -=。 同時,它說“許多有用的操作不需要直接訪問復數的表示,因此可以將它們與 class 定義分開定義”。
現在,當我嘗試以下代碼時:
#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; }
我收到一個鏈接錯誤: class Complex_cdecl operator+(class Complex, class Complex)
已經在Complex.obj
中定義 找到一個或多個多重定義的符號。
所以,我想本書中提供的代碼只是部分的。 我不知道什么是overload
+
和+=
的正確方法。 這本書是錯的還是過時的?
謝謝你的幫助。
在您的示例中, operator +
應該inline
,以便 linker 知道多個 obj 文件可以包含相同的 function 定義。
inline Complex operator+ (Complex a, Complex b) { return a += b; }
或者 header 文件應該只包含聲明
Complex operator+ (Complex a, Complex b);
並且只有一個 cpp 文件應該包含定義
Complex operator+ (Complex a, Complex b) { return a += b; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.