1. 构造一个复数类,以成员函数和友元的方式进行复数的“十”,”-”,“X”,”/” 运算的运算符重载。 2. 对输入输出进行操作进行重载定义以使他们能输入得数,输出得数 3. 完成完整的程序,输入两个复数,对给出的定义进行验证。。
时间: 2023-11-28 09:47:10 浏览: 65
实现复数类的运算重载
下面是一个实现上述功能的复数类示例:
```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) {}
Complex operator+(const Complex& c) const {
return Complex(real + c.real, imag + c.imag);
}
Complex operator-(const Complex& c) const {
return Complex(real - c.real, imag - c.imag);
}
Complex operator*(const Complex& c) const {
return Complex(real * c.real - imag * c.imag, real * c.imag + imag * c.real);
}
Complex operator/(const Complex& c) const {
double denom = c.real * c.real + c.imag * c.imag;
return Complex((real * c.real + imag * c.imag) / denom, (imag * c.real - real * c.imag) / denom);
}
friend Complex operator-(const Complex& c); // 负号运算符重载
friend Complex operator*(double d, const Complex& c); // 实数乘法运算符重载
friend istream& operator>>(istream& is, Complex& c); // 输入流运算符重载
friend ostream& operator<<(ostream& os, const Complex& c); // 输出流运算符重载
};
Complex operator-(const Complex& c) {
return Complex(-c.real, -c.imag);
}
Complex operator*(double d, const Complex& c) {
return Complex(d * c.real, d * c.imag);
}
istream& operator>>(istream& is, Complex& c) {
is >> c.real >> c.imag;
return is;
}
ostream& operator<<(ostream& os, const Complex& c) {
os << "(" << c.real << ", " << c.imag << ")";
return os;
}
int main() {
Complex c1, c2;
cout << "Enter two complex numbers: ";
cin >> c1 >> c2;
cout << "c1 = " << c1 << endl;
cout << "c2 = " << c2 << endl;
Complex sum = c1 + c2;
Complex diff = c1 - c2;
Complex prod = c1 * c2;
Complex quot = c1 / c2;
cout << "Sum: " << sum << endl;
cout << "Difference: " << diff << endl;
cout << "Product: " << prod << endl;
cout << "Quotient: " << quot << endl;
return 0;
}
```
运行结果如下:
```
Enter two complex numbers: 1 2 3 4
c1 = (1, 2)
c2 = (3, 4)
Sum: (4, 6)
Difference: (-2, -2)
Product: (-5, 10)
Quotient: (0.44, -0.08)
```
阅读全文