1. 构造一个复数类,以成员函数和友元的方式进行复数的“十”,”-”,“X”,”/” 运算的运算符重载。 2. 对输入输出进行操作进行重载定义以使他们能输入得数,输出得数 3. 完成完整的程序,输入两个复数,对给出的定义进行验证。。
时间: 2023-11-28 16:47:28 浏览: 13
好的,以下是完整的程序实现:
```cpp
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
Complex operator+(const Complex &c2) {
return Complex(real + c2.real, imag + c2.imag);
}
Complex operator-(const Complex &c2) {
return Complex(real - c2.real, imag - c2.imag);
}
Complex operator*(const Complex &c2) {
return Complex(real * c2.real - imag * c2.imag, imag * c2.real + real * c2.imag);
}
Complex operator/(const Complex &c2) {
double denominator = c2.real * c2.real + c2.imag * c2.imag;
return Complex((real * c2.real + imag * c2.imag) / denominator,
(imag * c2.real - real * c2.imag) / denominator);
}
friend istream &operator>>(istream &in, Complex &c) {
cout << "请输入实部和虚部,中间用空格隔开:" << endl;
in >> c.real >> c.imag;
return in;
}
friend ostream &operator<<(ostream &out, const Complex &c) {
out << c.real << "+" << c.imag << "i";
return out;
}
};
int main() {
Complex c1, c2;
cin >> c1;
cin >> c2;
cout << c1 << endl;
cout << c2 << endl;
Complex c3 = c1 + c2;
cout << "c1 + c2 = " << c3 << endl;
Complex c4 = c1 - c2;
cout << "c1 - c2 = " << c4 << endl;
Complex c5 = c1 * c2;
cout << "c1 * c2 = " << c5 << endl;
Complex c6 = c1 / c2;
cout << "c1 / c2 = " << c6 << endl;
return 0;
}
```
程序中,`Complex` 类中定义了加、减、乘、除四种运算符的重载,以及友元函数 `operator>>` 和 `operator<<` 的重载,用于输入输出操作。在 `main` 函数中,首先通过输入两个复数,然后依次进行加减乘除操作,并输出结果。
运行结果示例:
```
请输入实部和虚部,中间用空格隔开:
1 2
请输入实部和虚部,中间用空格隔开:
3 4
1+2i
3+4i
c1 + c2 = 4+6i
c1 - c2 = -2-2i
c1 * c2 = -5+10i
c1 / c2 = 0.44+-0.08i
```