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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值