天天看點

C++程式設計實驗報告(五十)---第七周任務三

#include <iostream>

using namespace std;

template<class type>

class Complex   
{
public:    
	Complex( ){real=0;imag=0;}  
	Complex(type r, type i){real = r; imag = i;} 
	Complex complex_add(Complex &c2); 
	void display( );   
private:
	type real; 
	type imag; 
};

template<class type>                                     //每次定義都必須寫

Complex<type> Complex<type>::complex_add(Complex<type> &c2)     //模闆類的對象做傳回值!
{
	Complex<type> c;

	c.real = real + c2.real;

	c.imag = imag + c2.imag;

	return c;
}

template<class type>

void Complex<type>::display( )   //模闆類一定要清楚的寫出,而傳回值是void
{
	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;
}

           

運作結果:

C++程式設計實驗報告(五十)---第七周任務三

感言:

小看了類模闆還真不行,以為還是極其簡單的,但實際是做了比任務一和二更多的時間,首先就是對于了解上的膚淺,泛泛的照貓畫虎,不了解實質,經過反複體會,才真正明白在類外定義的形式;其次是忘記了template的特殊,即在每次函數定義都應包含。