C++学习(27)

 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 }

 

posted on 2018-07-01 18:05  孙悟空son_ku_kong  阅读(135)  评论(0编辑  收藏  举报

导航