cppTest-3.5:模板類

/**
  *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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章