设计一个复数 Complex 类,用友元函数重载乘法运算符(*),用成员函数重 载除法运算符(D,完成两个复数对象的乘除法。 加法:(atbi) +(ctdi) = (atc) + (b+d)i; 减法:(a+bi)-(c+di) = (a-c) + (b-d)i; 乘法:(a+b
时间: 2023-10-27 20:05:56 浏览: 75
两个二维数组相加,用成员函数重载运算符“+”和“-”
5星 · 资源好评率100%
i) * (c+di) = (ac-bd) + (ad+bc)i;
除法: (a+bi) / (c+di) = ((ac+bd)/(c^2+d^2)) + ((bc-ad)/(c^2+d^2))i;
下面是Complex类的实现代码:
```cpp
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
friend Complex operator+(const Complex& a, const Complex& b);
friend Complex operator-(const Complex& a, const Complex& b);
friend Complex operator*(const Complex& a, const Complex& b);
friend Complex operator/(const Complex& a, const Complex& b);
void display() {
cout << real << "+" << imag << "i" << endl;
}
};
Complex operator+(const Complex& a, const Complex& b) {
return Complex(a.real + b.real, a.imag + b.imag);
}
Complex operator-(const Complex& a, const Complex& b) {
return Complex(a.real - b.real, a.imag - b.imag);
}
Complex operator*(const Complex& a, const Complex& b) {
return Complex(a.real * b.real - a.imag * b.imag, a.real * b.imag + a.imag * b.real);
}
Complex operator/(const Complex& a, const Complex& b) {
double denominator = b.real * b.real + b.imag * b.imag;
return Complex((a.real * b.real + a.imag * b.imag) / denominator,
(a.imag * b.real - a.real * b.imag) / denominator);
}
int main() {
Complex a(1, 2);
Complex b(3, 4);
Complex c = a + b;
c.display(); // 4+6i
Complex d = a - b;
d.display(); // -2-2i
Complex e = a * b;
e.display(); // -5+10i
Complex f = a / b;
f.display(); // 0.44+0.08i
return 0;
}
```
阅读全文