Complex.h
#ifndef _COMPLEX_H_
#define _COMPLEX_H_
class Complex{
friend std::istream& operator>>(std::istream& in,Complex&);
friend std::ostream& operator<<(std::ostream& out,Complex&);
public:
Complex();
Complex(float);
Complex(float,float);
Complex(const Complex&);
float getReal()const;
float getImg()const;
void setReal(float);
void setImg(float);
Complex operator+(const Complex&);
Complex operator-(const Complex&);
Complex operator*(const Complex&);
Complex operator/(const Complex&);
Complex& operator=(const Complex& op);
private:
float real;
float img;
};
#endif
Complex.cpp
#include<iostream>
#include "Complex.h"
using namespace std;
Complex::Complex()
{
real=0;
img=0;
}
Complex::Complex(float real)
{
this->real=real;
this->img=0;
}
Complex::Complex(float real,float img)
{
this->real=real;
this->img=img;
}
Complex::Complex(const Complex&op)
{
real=op.real;
img=op.img;
}
float Complex::getReal()const
{
return real;
}
float Complex::getImg()const
{
return img;
}
void Complex::setReal(float real)
{
this->real=real;
}
void Complex::setImg(float img)
{
this->img=img;
}
Complex Complex::operator+(const Complex& op)
{
Complex result;
result.real=real+op.real;
result.img=img+op.img;
return result;
}
Complex Complex::operator-(const Complex& op)
{
Complex result;
result.real=real-op.real;
result.img=img-op.img;
return result;
}
Complex Complex::operator*(const Complex& op)
{
Complex result;
result.real=real*op.real-img*op.img;
result.img=real*op.img+img*op.real;
return result;
}
Complex Complex::operator/(const Complex& op)
{
if(op.real==0&&op.img==0)
{
cerr<<"除数为0!"<<endl;
exit(-1);
}
Complex result;
double deno=op.real*op.real+op.img*op.img;
result.real=(real*op.real+img*op.img)/deno;
result.img=(img*op.real-real*op.img)/deno;
return result;
}
Complex& Complex::operator=(const Complex& op)
{
real=op.real;
img=op.img;
return *this;
}
istream& operator>>(istream& in,Complex&op)
{
return in>>op.real>>op.img;
}
ostream& operator<<(ostream& out,Complex&op)
{
if(op.real==0&&op.img==0)return out<<0<<endl;
if(op.real!=0)out<<op.real;
if(op.img==0)return out<<endl;
if(op.img>0)
{
if(op.real!=0)out<<"+";
if(op.img==1)out<<"i";
else out<<op.img<<"i";
}
else
{
if(op.img==-1)out<<"-i";
else out<<op.img<<"i";
}
return out<<endl;
}
main.cpp
#include<iostream>
#include "Complex.h"
using namespace std;
int main()
{
Complex comp1,comp2;
cin>>comp1>>comp2;
cout<<comp1+comp2<<comp1-comp2<<comp1*comp2;
cout<<comp1/comp2;
return 0;
}