函数模板与模板类

关键字:template,typename,class

template<class T>
T max(T a,Tb)   //函数模板
{
	return (a>b)? a:b;
}

int ival = max(100,99);  //模板函数
char cval=max<char> ('A','B');


template<typename T>
void swap(T &a,&T b)
{
	T tmp=a;
	a=b;
	b=tmp;
}

int x=20,y=30;
swap<int> (x,y);

变量作为模板参数

template<int size>
void display()
{
	cout<<size<<endl;
}

display<10>();

多参数函数模板

template<typename T, typename C>   //typename 、class 、变量参数可混用
void display(T a,C b)
{
	cout<<a<<" "<<b<<endl;
}

int a=1024; string str = "hello world!";
display<int ,string> (a,str);

以上在vc++6.0出现报错,转到此处解决


类模板

template<class T>
class MyArray
{
public:
	void display(){}
private:
	T  *a;
};

template<class T>  //每一个成员函数的定义前面都要加上这句
void MyArray<T>::display()
{}

void main()
{
	MyArray<int> arr;   //实例化对象arr
	arr.display();
}	

例子:

#include<iostream>
using namespace std;


template <typename T,int size,int num>
class MyArray{
public:
	MyArray();
	~MyArray()
	{
		delete []m_pArr;
		m_pArr=NULL;
	}
	void display();

private:
	T *m_pArr;
};


template<typename T,int size,int num>
MyArray<T,size,num>::MyArray()
{
	m_pArr=new T[size];
	for(int i=0;i<size;i++)
	{
		m_pArr[i]=num;
	}
}

template<typename T,int size,int num>
void MyArray<T,size,num>::display()
{
	for(int i=0;i<size;i++) cout<<m_pArr[i]<<" ";
}


void main()
{
	MyArray<int,5,6> arr;
	arr.display();
}

输出结果为:6 6 6 6 6

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值