要實現復數的加減操作符重載,可以重載加法運算符"+“和減法運算符”-"。以下是一個示例代碼:
#include <iostream>
class Complex {
public:
double real;
double imag;
Complex(double r, double i) : real(r), imag(i) {}
Complex operator+(const Complex& other) {
return Complex(real + other.real, imag + other.imag);
}
Complex operator-(const Complex& other) {
return Complex(real - other.real, imag - other.imag);
}
};
int main() {
Complex a(1.0, 2.0);
Complex b(3.0, 4.0);
Complex c = a + b;
Complex d = a - b;
std::cout << "a + b = " << c.real << " + " << c.imag << "i" << std::endl;
std::cout << "a - b = " << d.real << " + " << d.imag << "i" << std::endl;
return 0;
}
在上面的示例中,我們定義了一個名為Complex的類來表示復數,重載了加法運算符和減法運算符。在main函數中,我們創建了兩個復數a和b,并使用重載的加法和減法運算符來計算它們的和與差。最后輸出結果。
通過重載運算符,我們可以像內置類型一樣對自定義類對象進行加減操作,使得代碼更加直觀和易讀。