请定义一个复数类,以便下面的程序可以使用它来获得正确的结果。(提示:需要重载"<<"及">>",数乘运算最好通过友元函数重载)
时间: 2023-12-31 16:03:42 浏览: 88
以下是一个复数类的定义,其中包含重载运算符和友元函数:
```c++
#include <iostream>
using namespace std;
class Complex {
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);
friend Complex operator*(const Complex& c1, const Complex& c2);
friend Complex operator*(const Complex& c, double n);
friend Complex operator*(double n, const Complex& c);
friend Complex operator/(const Complex& c1, const Complex& c2);
friend ostream& operator<<(ostream& os, const Complex& c);
friend istream& operator>>(istream& is, Complex& c);
private:
double real, imag;
};
Complex operator+(const Complex& c1, const Complex& c2) {
return Complex(c1.real + c2.real, c1.imag + c2.imag);
}
Complex operator-(const Complex& c1, const Complex& c2) {
return Complex(c1.real - c2.real, c1.imag - c2.imag);
}
Complex operator*(const Complex& c1, const Complex& c2) {
return Complex(c1.real * c2.real - c1.imag * c2.imag, c1.real * c2.imag + c1.imag * c2.real);
}
Complex operator*(const Complex& c, double n) {
return Complex(c.real * n, c.imag * n);
}
Complex operator*(double n, const Complex& c) {
return Complex(c.real * n, c.imag * n);
}
Complex operator/(const Complex& c1, const Complex& c2) {
double r = c2.real * c2.real + c2.imag * c2.imag;
return Complex((c1.real * c2.real + c1.imag * c2.imag) / r, (c1.imag * c2.real - c1.real * c2.imag) / r);
}
ostream& operator<<(ostream& os, const Complex& c) {
os << "(" << c.real << ", " << c.imag << "i)";
return os;
}
istream& operator>>(istream& is, Complex& c) {
is >> c.real >> c.imag;
return is;
}
```
现在,我们可以使用该类来进行复数运算,如下所示:
```c++
int main() {
Complex a(1, 2), b(2, 3);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "a + b = " << a + b << endl;
cout << "a - b = " << a - b << endl;
cout << "a * b = " << a * b << endl;
cout << "a * 2 = " << a * 2 << endl;
cout << "2 * a = " << 2 * a << endl;
cout << "a / b = " << a / b << endl;
Complex c;
cout << "Enter a complex number: ";
cin >> c;
cout << "The complex number you entered is " << c << endl;
return 0;
}
```
输出结果为:
```
a = (1, 2i)
b = (2, 3i)
a + b = (3, 5i)
a - b = (-1, -1i)
a * b = (-4, 7i)
a * 2 = (2, 4i)
2 * a = (2, 4i)
a / b = (0.615385, -0.0769231i)
Enter a complex number: 3 4
The complex number you entered is (3, 4i)
```
阅读全文