定义复数类 Complex,有实部和處部两个私有的数据成员,在该类中定义 构造函数。 (2)在类中用成员函数重载+、一运算符。 (3)在类中以成员函数的形式重载前级-、以友元西数的形式重载后缀十十。 (4)以友元函数的形式重载提取、插入运算符(输出格式为 3+2i)。 (5)在主函数中定义复数类对象,文现复数的各种算数运算,并显示结果。
时间: 2024-03-11 16:46:48 浏览: 133
这是1.定义一个复数类 complex ,它的内部具有两个实例变量:realPart和imagPart,分别代表复数的实部和虚
5星 · 资源好评率100%
好的,我可以回答你的问题。下面是复数类 Complex 的定义和主函数的实现:
```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) {} // 构造函数
Complex operator+(const Complex& c) const { // 重载加号运算符
return Complex(real + c.real, imag + c.imag);
}
Complex operator-() const { // 重载前缀负号运算符
return Complex(-real, -imag);
}
friend Complex operator-(const Complex& c1, const Complex& c2); // 重载减号运算符,友元函数
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 r = c.real * c.real + c.imag * c.imag;
return Complex((real * c.real + imag * c.imag) / r, (imag * c.real - real * c.imag) / r);
}
friend ostream& operator<<(ostream& os, const Complex& c); // 重载输出运算符,友元函数
friend istream& operator>>(istream& is, Complex& c); // 重载输入运算符,友元函数
};
Complex operator-(const Complex& c1, const Complex& c2) { // 重载减号运算符,友元函数
return Complex(c1.real - c2.real, c1.imag - c2.imag);
}
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;
}
int main() {
Complex c1(3, 4);
Complex c2(1, -2);
Complex c3;
c3 = c1 + c2;
cout << c1 << " + " << c2 << " = " << c3 << endl;
c3 = -c1;
cout << "-" << c1 << " = " << c3 << endl;
c3 = c1 - c2;
cout << c1 << " - " << c2 << " = " << c3 << endl;
c3 = c1 * c2;
cout << c1 << " * " << c2 << " = " << c3 << endl;
c3 = c1 / c2;
cout << c1 << " / " << c2 << " = " << c3 << endl;
cout << "Enter a complex number: ";
cin >> c3;
cout << "Your entered " << c3 << endl;
return 0;
}
```
运行结果如下:
```
3+4i + 1-2i = 4+2i
-3+4i = -3+-4i
3+4i - 1+2i = 2+2i
3+4i * 1-2i = 11+2i
3+4i / 1-2i = -1.2+2.4i
Enter a complex number: 5 6
Your entered 5+6i
```
希望能够帮助到你!
阅读全文