求兩個復數的加減乘除。
輸入描述
第一行兩個double類型數,表示第一個復數的實部虛部
第二行兩個double類型數,表示第二個復數的實部虛部
輸出描述
輸出依次計算兩個復數的加減乘除,一行一個結果
輸出復數先輸出實部,空格,然後是虛部,
樣例輸入
1 1 3 -1
樣例輸出
4 0 -2 2 4 2 0.2 0.4
1 #include <cstdio>
2 #include <cstring>
3 #include <iostream>
4 #include <algorithm>
5
6 using namespace std;
7
8 class Complex{
9 public:
10 Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {};
11 Complex operator+ (const Complex &c2) const;
12 Complex operator- (const Complex &c2) const;
13
14 /*實現下面三個函數*/
15 Complex operator* (const Complex &c2) const;
16 Complex operator/ (const Complex &c2) const;
17 friend ostream & operator<< (ostream &out, const Complex &c);
18
19 private:
20 double real;
21 double imag;
22 };
23
24 Complex Complex::operator+ (const Complex &c2) const {
25 return Complex(real + c2.real, imag + c2.imag);
26 }
27
28 Complex Complex::operator- (const Complex &c2) const {
29 return Complex(real - c2.real, imag - c2.imag);
30 }
31
32 Complex Complex::operator* (const Complex &c2) const
33 {
34 return Complex(real*c2.real - imag*c2.imag, real*c2.imag + imag*c2.real);
35 }
36
37 Complex Complex::operator/ (const Complex &c2) const
38 {
39 if (c2.imag == 0)
40 return Complex(real / c2.real, imag / c2.real);
41 else
42 return (*this)*Complex(c2.real, -c2.imag) / Complex(c2.real*c2.real + c2.imag*c2.imag, 0);
43 }
44
45 ostream & operator<< (ostream &out, const Complex &c)
46 {
47 out << c.real << " " << c.imag << endl;
48 return out;
49 }
50
51 int main() {
52 double real, imag;
53 cin >> real >> imag;
54 Complex c1(real, imag);
55 cin >> real >> imag;
56 Complex c2(real, imag);
57 cout << c1 + c2;
58 cout << c1 - c2;
59 cout << c1 * c2;
60 cout << c1 / c2;
61 }
就是C++對操作符的重載。
有兩個地方要注意:
1、對 << 的重載中,注意要返回 out,這樣就可以實現 << 的級聯輸出(多項並列時);
2、對 / 的重載中,注意 return (*this)*Complex(c2.real, -c2.imag) / Complex(c2.real*c2.real + c2.imag*c2.imag, 0); 這一句是會繼續調用這個重載函數本身的!它本身就是對 / 的重載,而你在這裡又用到了 / ,所以會遞歸下去!所以必須加 return Complex(real / c2.real, imag / c2.real); 讓遞歸歸於平凡的情形(實際上只會遞歸一層)。