Complex類的一個完整定義,包括一個構造函數(Constructor)和兩個重載運算符(Overloaded Operators)+和-。這些方法允許你創建Complex對象並執行加法和減法操作。
cpp
class Complex {
public:
// 構造函數
Complex(double realPart = 0.0, double imaginaryPart = 0.0)
: real(realPart), imaginary(imaginaryPart) {}
// 加法運算符重載
Complex operator+(const Complex &operand2) const {
return Complex(real + operand2.real, imaginary + operand2.imaginary);
}
// 減法運算符重載
Complex operator-(const Complex &operand2) const {
return Complex(real - operand2.real, imaginary - operand2.imaginary);
}
private:
double real; // 實數部分
double imaginary; // 虛數部分
};
解釋:
構造函數 Complex(double realPart = 0.0, double imaginaryPart = 0.0):這個構造函數有兩個參數,默認值都是0.0。這允許你創建一個沒有任何參數的Complex對象(這種情況下,它將創建一個實部和虛部都為0的複數),或者創建一個具有特定實部和虛部的複數。
加法運算符重載 operator+:這個方法接受另一個Complex對象作為參數,將它與當前對象相加,然後返回結果。這是通過分別加實部和虛部來完成的。
減法運算符重載 operator-:這個方法的工作方式與加法運算符類似,但它是執行減法。它接受另一個Complex對象作為參數,將當前對象與之相減,然後返回結果。
這樣定義之後,你就可以在你的C++程式中創建Complex對象,並使用+和-運算符來執行複數加減運算了。