* (程序頭部註釋開始)
* 程序的版權和版本聲明部分
* Copyright (c) 2011, 煙臺大學計算機學院學生
* All rights reserved.
* 文件名稱:實現了一個複數類
* 作 者:齊豔紅
* 完成日期: 2011年 4月 3日
*版 本 號:
* 對任務及求解方法的描述部分
*問題描述:通過模板類的技術手段,設計Complex,使實部和虛部的類型爲定義對象時用的實際類型。
* 程序輸出:
* 程序頭部的註釋結束*/
#include <iostream>
using namespace std;
template<class numtype>//定義類模板
class Complex
{
public:
Complex( ){real=0;imag=0;}
Complex(numtype r,numtype i){real=r;imag=i;}
Complex complex_add(Complex &c2); //加法
Complex complex_sub(Complex &c2);//減法
Complex complex_div(Complex &c2);//除法
Complex complex_mult(Complex &c2);//乘法
void display( );
private:
numtype real;
numtype imag;
};
//定義加法
template<class numtype>
Complex<numtype> Complex<numtype>::complex_add(Complex<numtype> &c2)
{
Complex<numtype> c;
c.real=real+c2.real;
c.imag=imag+c2.imag;
return c;
}
//定義減法
template<class numtype>
Complex<numtype> Complex<numtype>::complex_sub(Complex<numtype> &c2)
{
Complex<numtype> c;
c.real=real-c2.real;
c.imag=imag-c2.imag;
return c;
}
//定義除法
template<class numtype>
Complex<numtype> Complex<numtype>::complex_div(Complex<numtype> &c2)
{
Complex<numtype> c;
c.real = (real*c2.real + imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
c.imag = (-real*c2.imag + imag*c2.real)/(c2.real*c2.real+c2.imag*c2.imag);
return c;
}
//定義乘法
template<class numtype>
Complex<numtype> Complex<numtype>::complex_mult(Complex<numtype> &c2)
{
Complex<numtype> c;
c.real = real*c2.real - imag*c2.imag;
c.imag = real*c2.imag + imag*c2.real;
return c;
}
template<class numtype>
void Complex<numtype>::display( )
{
cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
int main( )
{ Complex<int> c1(3,4),c2(5,-10),c3,c7;
c3=c1.complex_add(c2);
cout<<"c1+c2=";
c3.display( );
c7=c1.complex_sub(c2);
cout<<"c1-c2=";
c7.display();
Complex<double> c4(3.1,4.4),c5(5.34,-10.21),c6,c8;
c6=c4.complex_div(c5);
cout<<"c4/c5=";
c6.display( );
c8=c4.complex_mult(c5);
cout<<"c4*c5=";
c8.display( );
system("pause");
return 0;
}
總結:說實話,這個程序的過程還不是很瞭解,這個報告是通過向同學求助完成的,有些細節問題還需弄清楚,雖然現在還有點問題,但我相信回去後再仔細琢磨琢磨也應該沒問題的!呵呵····