C++复数类对除法运算符 / 的重载

C8-1 复数加减乘除 

(100.0/100.0 points)
题目描述

求两个复数的加减乘除。

输入描述

第一行两个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); 让递归归于平凡的情形(实际上只会递归一层)。




原文地址:https://www.cnblogs.com/maples7/p/4520705.html