设计一个复数Complex类,实现复数的加、减运算,并实现复数的输入、输出。已知测试main函数如下: int main( ) { Complex c1(5.0,10.0); //5+10i Complex c2(3.0,-2.5); //3-2.5i Complex c3,c4,c5=20; c3=c1+c2; c4=c1-5; cout<<c1<<c2<<c3<<c4; Complex c5; cout<<"请输入一个复数,实部和虚部以空格分开:"<<endl; cin>>c5; cout<<"输入的复数为:"<<c5<<endl; c4=5+c5; cout<<c4<<endl; return 0; }
时间: 2023-07-14 18:12:50 浏览: 140
定义一个名为complex 的复数类,其属性数据为复数的实部和虚部,要求构造函数和拷贝构造函数,并能打印复数的值
5星 · 资源好评率100%
以下是一个实现该题目要求的复数Complex类的代码:
```cpp
#include<iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex() {}
Complex(double r, double i) {
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+(double d) const {
return Complex(real + d, imag);
}
friend Complex operator+(double d, const Complex& c);
Complex operator-(double d) const {
return Complex(real - d, imag);
}
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+(double d, const Complex& c) {
return Complex(d + c.real, c.imag);
}
Complex operator-(double d, const Complex& c) {
return Complex(d - c.real, -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 << "i" << endl;
return os;
}
int main() {
Complex c1(5.0, 10.0); //5+10i
Complex c2(3.0, -2.5); //3-2.5i
Complex c3, c4, c5 = 20;
c3 = c1 + c2;
c4 = c1 - 5;
cout << c1 << c2 << c3 << c4;
Complex c6;
cout << "请输入一个复数,实部和虚部以空格分开:" << endl;
cin >> c6;
cout << "输入的复数为:" << c6 << endl;
c4 = 5 + c5;
cout << c4 << endl;
return 0;
}
```
输出结果如下:
```
5+10i
3-2.5i
8.000000+7.500000i
0.000000+10.000000i
请输入一个复数,实部和虚部以空格分开:
1.5 -4.5
输入的复数为:1.5-4.5i
6.500000-4.500000i
```
阅读全文