现在的位置: 首页 > 综合 > 正文

第起周任务3

2013年02月21日 ⁄ 综合 ⁄ 共 1642字 ⁄ 字号 评论关闭
#include <iostream>

using namespace std;

template <class numtype>

class Complex
{
private:
 
 numtype real;
 numtype imag;
 
public:
 
 Complex(){real=0;imag=0;}
 
 Complex(numtype r,numtype i){real=r;imag=i;}
 
 Complex add(Complex x2);

 Complex minus(Complex x2);

 Complex multiply(Complex x2);

 Complex divide(Complex x2);

 void display();
};
template <class numtype>////////////////////////////////拉了

Complex<numtype> Complex<numtype>::add(Complex<numtype> x2)////////////////////类外定义结构不对,声明x2时,课本上直接是complex
{
 Complex<numtype> x;/////////////无括号内容

 x.real=real+x2.real;
 
 x.imag=imag+x2.imag;
 
 return x;
}
template <class numtype>

Complex<numtype> Complex<numtype>::minus(Complex<numtype> x2)
{
 Complex<numtype> x;

 x.real=real-x2.real;
 
 x.imag=imag-x2.imag;
 
 return x;
}
template <class numtype>

Complex<numtype> Complex<numtype>::multiply(Complex<numtype> x2)
{
 Complex<numtype> x;

 x.real=real*x2.real;
 
 x.imag=imag*x2.imag;
 
 return x;
}
template <class numtype>

Complex<numtype> Complex<numtype>::divide(Complex<numtype> x2)
{
 Complex<numtype> x;

 x.real=real/x2.real;
 
 x.imag=imag/x2.imag;
 
 return x;
}


template <class numtype>////////////////////////////////拉了,原来所有的函数都要加

void Complex<numtype>::display()///////////////////////拉括号内容了。
{
 cout<<'('<<real<<','<<imag<<"i)"<<endl;
}
int main( )
{
 Complex<int> c1(3,4),c2(5,-10);
    Complex<int>  c3;
 c3=c1.add(c2);  
    cout<<"c1+c2="; 
    c3.display( );  
    cout<<"c1*c2="; 
 c3=c1.multiply(c2);
    c3.display( );  
    Complex<double> c4(3.1,4.4); 
    Complex<double> c5(5.34,-10.21);
    Complex<double> c6;
    c6=c4.add(c5);  
    cout<<"c4+c5="; 
    c6.display( ); 
    cout<<"c4/c5=";
    c6=c4.divide(c5);  
    c6.display( ); 
   //system("pause");
    return 0;
}

 

感悟:1:开始认为,只有涉及到变量 的函数在类外定义时前面才加例如“template <class numtype>"的声明类模板,谁知所有的函数在声明时前面都要加。:

2:template<class numtype >中的numtype只是虚拟类型,无实际的含义,可可以在以后的定义对象中,被其他类型取代。

抱歉!评论已关闭.