cppTest-3.5:模板类

来源:互联网 发布:北京网络信息传媒公司 编辑:程序博客网 时间:2024/06/05 10:34
/**  *cppTest-3.5:模板类@@在类模板中可以声明三种友元函数:    (1)一般的友元函数。这种友元函数中不使用任何类模板中的类型参数表列中的参数。(即不使用类型模板的友元函数)    (2)封闭型类模板友元函数。(使用类的类型模板的友元函数)    (3)开放型类模板友元函数。(不使用类的类型模板而使用自己定义的类型模板的友元函数) *author 炜sama */#include<iostream.h>#include<conio.h>const int ArraySize=8;//与模板函数的用法差不多,template<class Type>放在类定义前,template<class Type>//int i;//中间不能插入任何代码!class Array{friend ostream& operator<<(ostream& os,Array<Type>& array);private:Type *element;int size;public:Array(const int s){size=s;element=new Type[size];for(int i=0;i<size;i++)element[i]=0;}~Array(){ delete element;}Type& operator[](const int index);void operator=(Type temp);template<class T>friend void print(T t);};template<class Type>//定义类里面声明的模板函数时这里还要再次声明这个类型Type说明!不然函数不知道Type是神马~Type& Array<Type>::operator[](const int index){return element[index];}template<class Type>void Array<Type>::operator=(Type temp){for(int i=0;i<size;i++)element[i]=temp;}template<class Type>ostream& operator<<(ostream& os,Array<Type>& array){for(int i=0;i<array.size;i++)os<<array.element[i]<<endl;return os;}template<class T>void print(T t){cout<<t;}void main(){//define objects of template class'Array'Array<int>IntObj(ArraySize);Array<double>DoubleObj(ArraySize);Array<char>CharObj(ArraySize);IntObj=518;DoubleObj=3.14159;CharObj='A';cout<<"The integer type class:"<<endl<<IntObj;cout<<"The double floating type class:"<<endl<<DoubleObj;cout<<"The character type class:"<<endl<<CharObj;}

0 0
原创粉丝点击