请设计复数类Complex,实现复数的算术、赋值运算符的重载。 输入三行,每行是一个复数的实部和虚部。 输出两行,分别是c1+c2+c3,c1*c2*c3的值。 C++
时间: 2024-05-05 11:17:39 浏览: 61
++代码如下:
```
#include<iostream>
using namespace std;
class Complex{
public:
Complex(double real_=0.0,double imag_=0.0):real(real_),imag(imag_){}
Complex operator+(const Complex& a)const{
return Complex(real+a.real,imag+a.imag);
}
Complex operator-(const Complex& a)const{
return Complex(real-a.real,imag-a.imag);
}
Complex operator*(const Complex& a)const{
return Complex(real*a.real-imag*a.imag,real*a.imag+imag*a.real);
}
Complex operator/(const Complex& a)const{
double denominator=a.real*a.real+a.imag*a.imag;
return Complex((real*a.real+imag*a.imag)/denominator,(imag*a.real-real*a.imag)/denominator);
}
Complex operator+=(const Complex& a){
real+=a.real;
imag+=a.imag;
return *this;
}
Complex operator-=(const Complex& a){
real-=a.real;
imag-=a.imag;
return *this;
}
Complex operator*=(const Complex& a){
double temp_real=real*a.real-imag*a.imag;
imag=real*a.imag+imag*a.real;
real=temp_real;
return *this;
}
Complex operator/=(const Complex& a){
double denominator=a.real*a.real+a.imag*a.imag;
double temp_real=(real*a.real+imag*a.imag)/denominator,
temp_imag=(imag*a.real-real*a.imag)/denominator;
real=temp_real;
imag=temp_imag;
return *this;
}
Complex operator=(const Complex& a){
real=a.real;
imag=a.imag;
return *this;
}
friend ostream& operator<<(ostream& os,const Complex& n){
os<<n.real<<'+'<<n.imag<<"i";
return os;
}
friend istream& operator>>(istream& is,Complex& n){
is>>n.real>>n.imag;
return is;
}
private:
double real,imag;
};
int main(){
Complex c1,c2,c3;
cin>>c1>>c2>>c3;
Complex ans=c1*c2*c3;
cout<<c1<<endl<<c2<<endl<<c3<<endl<<ans<<endl;
return 0;
}
```
阅读全文