/* (程序頭部註釋開始)
* 程序的版權和版本聲明部分
* Copyright (c) 2011, 煙臺大學計算機學院學生
* All rights reserved.
* 文件名稱: 類成員函數
* 作 者: 王琳
* 完成日期: 2012 年 4 月 4日
* 版 本 號: 7-3
* 對任務及求解方法的描述部分
* 問題描述:該例實現了一個複數類,但是美中不足的是,複數類的實部和虛部都固定是double型的。可以通過模板類的技術手段,設計Complex,使實部和虛部的類型爲定義對象時用的實際類型。
(1)要求類成員函數在類外定義。
(2)在此基礎上,再實現減法、乘法和除法
* 程序頭部的註釋結束
*/
源程序:
#include <iostream>
using namespace std;
template <class numtype>
class Complex
{
public:
Complex( )
{
real=0;
imag=0;
}
Complex(double r,double i)
{
real=r;
imag=i;
}
Complex complex_add(Complex &c2);
void display( );
private:
numtype real;
numtype imag;
};
template <class numtype>
Complex<numtype> Complex<numtype>::complex_add(Complex &c2)
{
Complex<numtype> 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( );
system("pause");
return 0;
}
運行結果:
感想:各種方法,各種不同,各種糾結,歸根結底還是得看課本啊!這個任務練習了類外定義函數,對基本方法還是有所瞭解了,有收穫啊!