Complex复数类
Complex.h
# ifndef COMPLEX_H
# define COMPLEX_H
# include <iostream>
using namespace std;
class Complex
{
private :
double real = 0 ;
double imag = 0 ;
public :
Complex ( ) = default ;
Complex ( double r) ;
Complex ( double a, double b) ;
Complex operator - ( ) ;
friend Complex operator + ( const Complex& Z1 , const Complex& Z2) ;
Complex& operator += ( const Complex& Z2) ;
friend bool operator == ( const Complex& Z1, const Complex& Z2) ;
friend bool operator != ( const Complex& Z1, const Complex& Z2) ;
friend ostream& operator << ( ostream& output, const Complex& Z) ;
friend istream& operator >> ( istream& input, const Complex& Z) ;
Complex & operator ++ ( ) ;
Complex operator ++ ( int ) ;
Complex & operator ( ) ( double a, double b) ;
explicit operator unsigned int ( ) const ;
} ;
# endif
Complex.c
# include "Complex.h"
Complex :: Complex ( double r) : real ( r) { }
Complex :: Complex ( double a, double b) : real ( a) , imag ( b) { }
Complex Complex:: operator - ( )
{
Complex temp;
temp. real = - real;
temp. imag = - imag;
return temp;
}
Complex operator + ( const Complex& Z1, const Complex& Z2)
{
Complex temp;
temp. real = Z1. real + Z2. real;
temp. imag = Z1. imag + Z2. imag;
return temp;
}
Complex& Complex:: operator += ( const Complex& Z2)
{
real += Z2. real;
imag += Z2. imag;
return * this ;
}
bool operator == ( const Complex& Z1, const Complex& Z2)
{
if ( Z1. real == Z2. real && Z1. imag == Z2. imag)
return true ;
else
return false ;
}
bool operator != ( const Complex& Z1, const Complex& Z2)
{
if ( Z1. real == Z2. real && Z1. imag == Z2. imag)
return false ;
else
return true ;
}
ostream& operator << ( ostream& output, const Complex& Z)
{
output << Z. real << " + " << Z. imag << 'i' ;
return output;
}
istream& operator >> ( istream& input, const Complex& Z)
{
input >> Z. real >> Z. imag;
return input;
}
Complex & Complex:: operator ++ ( )
{
real += 1 ;
imag += 1 ;
return * this ;
}
Complex Complex:: operator ++ ( int )
{
Complex temp;
temp. real = real;
temp. imag = imag;
real += 1 ;
imag += 1 ;
return temp;
}
Complex& Complex :: operator ( ) ( double a, double b)
{
real = a;
imag = b;
return * this ;
}
Complex:: operator unsigned int ( ) const
{
return real;
}
main.c
# include "Complex.h"
# include "Shape.h"
# include <iostream>
using namespace std;
void Complex_Test ( void )
{
Complex Z;
Z ( 1 , 1 ) ;
cout << Z << endl;
cout << ( unsigned int ) Z << endl;
Complex Z3{ 12 } ;
cout << Z3 << endl;
Complex Z1{ 3 , 4 } ;
cout << "Z1 = " << Z1 << endl;
Complex Z2{ 2 , 1 } ;
cout << "Z2 = " << Z2 << endl;
Z = - Z1;
cout << "-Z1 = " << Z << endl;
Z = Z1 + Z2;
cout << "Z1+Z2 = " << Z << endl;
Z += { 2 , 2 } ;
cout << "Z+{2,2} = " << Z << endl;
Z = Z1++ ;
cout << "Z1++ = " << Z << endl;
Z = ++ Z2;
cout << "++Z2 = " << Z << endl;
if ( Z1 != Z2)
cout << "不相等" << endl;
else
cout << "相等" << endl;
}
int main ( void )
{
Complex_Test ( ) ;
return 0 ;
}
结果: