用C++设计一个complex类并用友元函数重载乘法运算符实现两复数的乘除法
时间: 2024-02-11 19:06:07 浏览: 140
【例6.4】用友元函数重载运算符实现两字符串加法.docx
好的,下面是实现代码:
```c++
#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);
friend complex operator/(const complex &c1, const complex &c2);
void print() {
cout << "(" << real << "," << imag << ")" << 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 operator/(const complex &c1, const complex &c2) {
double r = (c1.real * c2.real + c1.imag * c2.imag) / (c2.real * c2.real + c2.imag * c2.imag);
double i = (c1.imag * c2.real - c1.real * c2.imag) / (c2.real * c2.real + c2.imag * c2.imag);
return complex(r, i);
}
int main() {
complex c1(1, 2), c2(3, 4);
complex c3 = c1 * c2;
complex c4 = c1 / c2;
c3.print();
c4.print();
return 0;
}
```
解释一下:
- `complex` 类表示复数,有实部和虚部两个数据成员;
- 构造函数用于初始化实部和虚部;
- `operator*` 和 `operator/` 是友元函数,用来重载乘法和除法运算符;
- `print` 函数用于输出复数。
在 `main` 函数中,创建两个复数 `c1` 和 `c2`,并计算它们的积 `c3` 和商 `c4`,最后输出 `c3` 和 `c4`。
阅读全文