模板类

#include<iostream>

#include<algorithm>sort

using namespace std;

template<class ElemType>

class Array

{

         private:

                   ElemType *elem;

                   int size;

         public:

                   Array(ElemType a[],int sz):elem(a),size(sz){};

                   ElemType Max();

                   ElemType Sum();

                   void Sort();

                   void Show();

};

template <class ElemType>

ElemType Array<ElemType>::Max()

{

         ElemType max=elem[0];

         for(int i=1;i<size;i++)

                   if(elem[i]>max)

                            max=elem[i];

         return max;

}

template<class ElemType>

ElemType Array<ElemType>::Sum()

{

         ElemType sum=0;

         for(int i=0;i<size;i++)

                   sum+=elem[i];

         return sum;

}

template<class ElemType>

void Array<ElemType>::Sort()

{

         sort(elem,elem+size);

}

template<class ElemType>

void Array<ElemType>::Show()

{

         for(int i=0;i<size;i++)

                   cout<<elem[i]<<'\t';

         cout<<endl;

}

void main()

{

         int *p=new int[6];

         cout<<"请输入6个数据:"<<endl;

         for(int i=0;i<6;i++)

                   cin>>p[i];

         Array<int>obj(p,6);

         cout<<"最大值为:"<<obj.Max()<<endl;

         cout<<"元素之和为:"<<obj.Sum()<<endl;

         obj.Sort();

         cout<<"排序后数组各元素的值:"<<endl;

         obj.Show();

         system("pause");

}

posted @ 2012-11-22 23:06  ♂咱說 ろ算  阅读(157)  评论(0编辑  收藏  举报