源程序:
/* (程序頭部註釋開始)
* 程序的版權和版本聲明部分
* Copyright (c) 2011, 煙臺大學計算機學院學生
* All rights reserved.
* 文件名稱: 模板類
* 作 者: 114-3 張宗佳
* 完成日期: 2012 年 4 月 3 日
* 版 本 號: vc.3
* 對任務及求解方法的描述部分
* 輸入描述:
* 問題描述:該例實現了一個複數類,但是美中不足的是,複數類的實部和虛部都固定是double型的。
* 可以通過模板類的技術手段,設計Complex,使實部和虛部的類型爲定義對象時用的實際類型。
* 程序輸出:(1)要求類成員函數在類外定義。(2)在此基礎上,再實現減法、乘法和除法
* 程序頭部的註釋結束
*/
#include <iostream>
using namespace std;
template<class numtype>
class Complex
{
public:
Complex<numtype> ( ){real = 0;imag = 0;} //在聲明構造函數和成員函數時,類名後一定要跟有<類型參數>
Complex<numtype> (numtype r,numtype i){real = r;imag = i;}
Complex<numtype> complex_add(Complex &c2);
Complex<numtype> complex_cut(Complex &c2);
Complex<numtype> complex_multiply(Complex &c2);
Complex<numtype> complex_division(Complex &c2);
void display( );
private:
numtype real;
numtype imag;
};
template<class numtype>//在類外定義構造函數或成員函數時,要在前面加上template<class 類型參數>
Complex<numtype> Complex<numtype>::complex_add(Complex &c2)
{
Complex c;
c.real = real + c2.real;
c.imag = imag + c2.imag;
return c;
}
template<class numtype>
Complex<numtype> Complex<numtype>::complex_cut(Complex &c2)
{
Complex c;
c.real = real - c2.real;
c.imag = imag - c2.imag;
return c;
}
template<class numtype>
Complex<numtype> Complex<numtype>::complex_multiply(Complex &c2)
{
Complex c;
c.real = real * c2.real;
c.imag = imag * c2.imag;
return c;
}
template<class numtype>
Complex<numtype> Complex<numtype>::complex_division(Complex &c2)
{
Complex c;
c.real = real / c2.real;
c.imag = imag / c2.imag;
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;
c3 = c1.complex_add(c2);
cout << "c1+c2=";
c3.display( );
Complex<double> c4(3.1,4.4),c5(5.34,-10.21),c6;
c6 = c4.complex_add(c5);
cout << "c4+c5=";
c6.display( );
Complex<int> d1(3,4),d2(5,-10),d3;
d3 = d1.complex_cut(d2);
cout << "d1-d2=";
d3.display( );
Complex<double> d4(3.1,4.4),d5(5.34,-10.21),d6;
d6 = d4.complex_multiply(d5);
cout << "d4*d5=";
d6.display( );
Complex<int> b1(3,4),b2(5,-10),b3;
b3 = b1.complex_multiply(b2);
cout << "b1*b2=";
b3.display( );
system("pause");
return 0;
}
實驗結果:
經驗積累:
1.在聲明構造函數和成員函數時,類名後一定要跟有<類型參數>
2.在類內定義成員函數時可以用一般定義類成員函數的形式
3.而在類外定義成員函數時必須先聲明類模板,在前面加上template<class 類型參數>