用c++写设计一个复数Complex类,用友元函数重载乘法运算符(*),用成员函数重载除法运算符(/),完成两个复数对象的乘除法。
时间: 2024-02-09 20:12:55 浏览: 40
好的,以下是实现代码:
```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& c1, const Complex& c2);
Complex operator/(const Complex& c);
void display() {
cout << real << " + " << imag << "i" << endl;
}
};
Complex operator*(const Complex& c1, const Complex& c2) {
double r = c1.real * c2.real - c1.imag * c2.imag;
double i = c1.real * c2.imag + c1.imag * c2.real;
return Complex(r, i);
}
Complex Complex::operator/(const Complex& c) {
double denominator = c.real * c.real + c.imag * c.imag;
double r = (real * c.real + imag * c.imag) / denominator;
double i = (imag * c.real - real * c.imag) / denominator;
return Complex(r, i);
}
int main() {
Complex c1(1, 2);
Complex c2(3, 4);
Complex c3 = c1 * c2;
cout << "c1 * c2 = ";
c3.display();
Complex c4 = c1 / c2;
cout << "c1 / c2 = ";
c4.display();
return 0;
}
```
在上面的代码中,我们定义了一个名为 `Complex` 的类,该类表示复数,其中包含了实部和虚部两个私有数据成员。类中定义了两个运算符重载函数,分别是:
- 友元函数 `operator*`,用于重载乘法运算符,实现两个复数对象的乘法操作;
- 成员函数 `operator/`,用于重载除法运算符,实现两个复数对象的除法操作。
在主函数中,我们创建了两个 `Complex` 对象 `c1` 和 `c2`,并分别进行了乘法和除法运算,并将结果存储在 `c3` 和 `c4` 中。最后,我们调用 `display` 函数输出结果。