607a.cpp

来自「C++实训教程」· C++ 代码 · 共 112 行

CPP
112
字号
/*
	607a.cpp
	Written By S.Y.Feng
	demo template class Complex       Complex with template
*/
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
template <class Type>
class Complex
{
private:
	Type real, imag;
public:
	Complex(Type re,Type im)
  { real=re;  imag=im;  }
  Complex()
  { real=0;  imag=0;  }
  Complex operator + (const Complex&c);
  Complex operator - (const Complex&c);
  Complex operator * (const Complex&c);
  Complex operator / (const Complex&c);
  Complex operator + (const Type d);
  Complex operator - (const Type d);
  Complex operator * (const Type d);
  Complex operator / (const Type d);
  void Disp(const Complex& c)
  { if(c.imag<0)
          cout<<c.real<<c.imag<<"i\n";
    else
          cout<<c.real<<"+"<<c.imag<<"i\n";
  }
};

template<class Type>
inline Complex Complex<Type>::operator + (const Complex&c)
{ return Complex<Type>(real+c.real,imag+c.imag);}

template<class Type>
inline Complex Complex<Type>::operator + (const Type d)
{ return Complex<Type>(real+d,imag);}
/*
template<class Type>
inline Complex Complex<Type>::operator+(const Type d,const Complex&c)
{ return Complex(c.real+d,c.imag);}
*/
template<class Type>
inline Complex Complex<Type>::operator - (const Complex&c)
{ return Complex<Type>(real-c.real,imag-c.imag);}


template<class Type>
inline Complex Complex<Type>::operator - (const Type d)
{ return Complex<Type>(real-d,imag);}
//template<class Type>
//inline Complex Complex<Type>::operator - (const Type d,const Complex&c)
//{ return Complex(d-c.real,c.imag);}

template<class Type>
inline Complex Complex<Type>::operator * (const Complex&c)
{ Type i,j;
i=real*c.real-imag*c.imag;
j=real*c.imag+imag*c.real;
return Complex<Type>(i,j);
}
template<class Type>
inline Complex Complex<Type>::operator * (const Type d)
{ return Complex<Type>(d*real,d*imag);}
//template<class Type>
//inline Complex Complex<Type>:: operator * (const Type d,const Complex&c)
//{ return Complex(d*c.real,d*c.imag);}

template<class Type>
inline Complex Complex<Type>::operator / (const Complex&c)
{ Type i,j,k;
i=real*c.real+imag*c.imag;
j=imag*c.real-real*c.imag;
k=c.real*c.real+c.imag*c.imag;
return Complex<Type>(i/k,j/k);
}
template<class Type>
inline Complex Complex<Type>::operator / (const Type d)
{ return Complex<Type>(real/d,imag/d);}

main()
{ 
	Complex <int>c1(5,7),*p;
	Complex <int>c2(8,-12),*q;
	Complex <int>c3,*r;
	p=&c1;
	q=&c2;
	p->Disp(c1);
	q->Disp(c2);
	c3=c1+c2;
	r=&c3;
	r->Disp(c3);
	c3=c1-c2;
	r->Disp(c3);
	c3=c1*c2;
	r->Disp(c3);
	c3=c1/c2;
	r->Disp(c3);
	return 0;
}
/*
5+7i
8-12i
13-5i
-3+19i
124-4i
0+0i
*/

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?