C++ 复数类怎么写?

2024-11-09 06:16:14
推荐回答(1个)
回答(1):

#include
#include
using namespace std;
class Complex{
private:
double Real,Image;
public:
Complex (double r=0.0,double i=0.0){Real=r;Image=i;}
Complex(Complex &com){
Real=com.Real;
Image=com.Image;
}
void Print(){
cout<<"Real="< }
Complex operator+(Complex);
Complex operator+(double);
Complex operator=(Complex);
Complex operator+=(Complex);
double abs(void);
Complex operator*(Complex);
Complex operator/(Complex);
};
Complex Complex::operator +(Complex c){
Complex temp(Real+c.Real,Image+c.Image);
return temp;
}
Complex Complex:: operator+(double d){
return Complex(Real+d,Image);
}
Complex Complex::operator =(Complex c){
Complex temp;
temp.Real=c.Real;
temp.Image=c.Image;
Real=temp.Real;
Image=temp.Image;
return temp;
}
Complex Complex::operator+=(Complex c){
Complex temp;
temp.Real=Real+c.Real;
temp.Image=Image+c.Image;
Real=temp.Real;
Image=temp.Image;
return temp;
}
double Complex::abs(void){
return sqrt(Real*Real+Image*Image);
}
Complex Complex::operator*(Complex c){

return Complex(Real*c.Real -Image*c.Image,Real*c.Image+c.Real *Image);
}
Complex Complex::operator/(Complex c){
double d=c.Real*c.Real+c.Image*c.Image;
return Complex((Real*c.Real+Image*c.Image)/d,(Image*c.Image-Real*c.Real)/d);
}
int main(){
Complex c1(1.0,1.0),c2(2.0,2.0),c3(4.0,4.0),c;

c1.Print();
double d=0.5;
c=c2+c3;c.Print();
c+=c1;c.Print();
c=c+d;c.Print();
c=c2*c3;c.Print();
c=c3/c1;c.Print();
cout<<"c3的模为:"< c=c3=c2=c1;c.Print();
c+=c2+=c1;c.Print();
return 0;

}