四、假設一個以 C++定義的複數 Complex 類別如下,請以 C++指令完整定義下列三個方法:
⑴建構子函式(Constructor):Complex()
⑵多載運算子(overloaded operator):+
⑶多載運算子:–
Complex()會作初始化動作,多載運算子 + 與 – 會將傳入之另一個 Complex 物件,
分別與現有的物件作加法或減法運算。(15 分)
class Complex {
public:
Complex( double = 0.0, double = 0.0 ); // 建構子
Complex operator+( const Complex & ) const; // 加法
Complex operator–( const Complex & ) const; // 減法
private:
double real; // 實數
double imaginary; // 虛數
};
詳解 (共 1 筆)
詳解
Complex類的一個完整定義,包括一個構造函數(Constructor)和兩個重載運算符(Overloaded Operators)+和-。這些方法允許你創建Complex對象並執行加法和減法操作。
cpp
class Complex {
public:
// 構造函數
Complex(double realPart = 0.0, double imaginaryPart = 0.0)
: real(realPart), imaginary(imaginaryPart) {}
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);
}
// 減法運算符重載
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的複數),或者創建一個具有特定實部和虛部的複數。
double real; // 實數部分
double imaginary; // 虛數部分
};
解釋:
構造函數 Complex(double realPart = 0.0, double imaginaryPart = 0.0):這個構造函數有兩個參數,默認值都是0.0。這允許你創建一個沒有任何參數的Complex對象(這種情況下,它將創建一個實部和虛部都為0的複數),或者創建一個具有特定實部和虛部的複數。
加法運算符重載 operator+:這個方法接受另一個Complex對象作為參數,將它與當前對象相加,然後返回結果。這是通過分別加實部和虛部來完成的。
減法運算符重載 operator-:這個方法的工作方式與加法運算符類似,但它是執行減法。它接受另一個Complex對象作為參數,將當前對象與之相減,然後返回結果。
這樣定義之後,你就可以在你的C++程式中創建Complex對象,並使用+和-運算符來執行複數加減運算了。