1. 程式人生 > >C++學習(27)

C++學習(27)

技術分享 TP emp IV int ble alt float real

 1 //類模板的學習
 2 //設計一個復數類模板
 3 //1.復數類模板的成員函數包括加和輸出
 4 //2.成員函數加既可以是兩個復數類模板對象相加,也可以是一個復數類模板對象和一個模板參數作為實部的數值相加
 5 //3.設計一個測試主函數,要求測試主函數中同時定義實際參數為float的復數類對象和實際參數為double的復數類對象
 6 
 7 #include<iostream.h>
 8 
 9 template <class T>
10 class Complex{
11     private:
12         T real;
13         T image;
14 public: 15 Complex(T x=0,T y=0); 16 ~Complex(){} 17 18 Complex Add(const Complex x)const; 19 Complex Add(const T x)const; 20 void show()const; 21 }; 22 23 template <class T> 24 Complex<T>::Complex(T x,T y){ 25 this->real=x; 26 this
->image=y; 27 } 28 29 30 template <class T> 31 Complex<T> Complex<T>::Add(const Complex x)const{ 32 return Complex<T>(this->real+x.real,this->image+x.image); 33 } 34 35 template <class T> 36 Complex<T> Complex<T>::Add(const T x)const{ 37 return
Complex<T>(this->real+x,this->image); 38 } 39 40 template <class T> 41 void Complex<T>::show()const{ 42 cout<<"real is "<<this->real<<endl; 43 cout<<"image is "<<this->image<<endl; 44 } 45 46 47 int main(){ 48 Complex<float>x(1.1,1.1),y(2.2,2.2),z; 49 z=x.Add(y); 50 cout<<"z is "; 51 z.show(); 52 53 Complex<double>u(1.111,1.111),v(2.222,2.222),w; 54 w=u.Add(v); 55 cout<<"w is "; 56 w.show(); 57 58 return 0; 59 }

技術分享圖片

C++學習(27)