#include<iostream>
using namespace std;
class complex
{
private:
double real;
double imaginary ;
public:
complex():real(0),imaginary(0){}
complex(double x,double y):real(x),imaginary(y){}
void operator = (const complex&c){
real=c.real;
imaginary=c.imaginary;
}
~complex(){}
complex operator- () {
return complex(-real,-imaginary);
}
complex operator+(const complex&c){
complex com;
com.real=real+c.real;
com.imaginary=imaginary+c.imaginary;
return com;
}
complex operator-(const complex&c){
complex com;
com.real = real - c.real;
com.imaginary = imaginary - c.imaginary;
return com;
}
complex operator*(const complex&c){
complex com ;
com.real = real*c.real - imaginary*c.imaginary;
com.imaginary = real*c.imaginary + imaginary*c.real;
return com;
}
complex operator/(const complex&c){
complex com;
double denominator = c.real*c.real + c.imaginary*c.imaginary;
com.real = (real*c.real + imaginary*c.imaginary)/denominator;
com.imaginary = (imaginary*c.real-real*c.imaginary)/denominator;
return com;
}
friend ostream &operator<<( ostream &output, const complex &c ){
output <<"( "<< c.real<<" ," <<c.imaginary<<" i )";
return output;
}
friend istream &operator>>( istream &input, complex &c ){
input >> c.real >> c.imaginary;
return input;
}
};
int main(){
complex a(4,6),b(2,-1);
cout<<a<<" + "<<b<<" = "<<a+b<<endl;
cout<<a<<" - "<<b<<" = "<<a-b<<endl;
cout<<a<<" * "<<b<<" = "<<a*b<<endl;
cout<<a<<" / "<<b<<" = "<<a/b<<endl;
return 0;
}
输出
( 4 ,6 i ) + ( 2 ,-1 i ) = ( 6 ,5 i )
( 4 ,6 i ) - ( 2 ,-1 i ) = ( 2 ,7 i )
( 4 ,6 i ) * ( 2 ,-1 i ) = ( 14 ,8 i )
( 4 ,6 i ) / ( 2 ,-1 i ) = ( 0.4 ,3.2 i )