c++模板机制

一、函数的模板

函数模板其实就是一个模子,用这个模子可以浇注出许多功能相同、参数类型和返回类型不同函数,从而实现代码的重用。一般的模板是template<class T>,当然新标准c++又增加了一个关键字typename,可以替换class,如:

template<typename T>

为了向下兼容,不建议用typename。废话少说,上程序:

#include<iostream>
using namespace std;
template< class T >
void printArray(const T *array ,const int count)
{


	for(int i=0;i<count;i++)
		cout<<array[i]<<" ";
	cout<<endl;




}


int main()
{
	const int aCount = 5;
	const int bCount = 7;
	const int cCount = 6;


	int a[aCount] = {1,2,3,4,5};
	double b[bCount] = { 1.1 , 2.2, 3.3, 4.4 ,5.5, 6.6, 7.7 };
	char c[cCount] = "Hello";


	cout<<"Array a contains : ";


	printArray(a,aCount);


	cout<<"Array b contains : ";
	printArray(b,bCount);




	cout<<"Array c contains : ";
	printArray(c,cCount);




	return 0;
}


执行的结果如下:

注意:模板凸显了软件重用的好处,尽管模板只编写了一次,但程序中仍需实例化多个模板函数和模板的副本,这些副本会占用大量的内存。


二、类模板



#ifndef TSTACK_H
#define TSTACK_H

template< class T>
class Stack
{

public:
Stack(int = 10);
~Stack()
{
delete [] stackPtr;//析构函数


}
bool push(const T&);
bool pop(T&);

bool isEmpty() const
{
return top == -1; //判断是否为空,若是空,返回真

}

bool isFull() const
{
return top == size -1; //判断栈是否已满,若已满,则返回真

}
private:
int size;
int top;
T *stackPtr;



};

template< class T >
Stack<T>::Stack(int s)
{
size = s >0 ? s :10;
top = -1;
stackPtr = new T[size]; //动态的创建一个T型数组,有stackPtr指向数组首地址


}
template< class T >
bool Stack<T>::push(const T &pushValue)
{

if(!isFull())
{

stackPtr[++top] = pushValue;
return true;

}
return false;

}

template< class T >
bool Stack<T>::pop( T &popValue)
{

if(!isEmpty())
{

popValue = stackPtr[top--];
return true;

}
return false;


}


#endif


PS:stack类的模板定义

#include<iostream>
using namespace std;
#include "tstack.h"

int main()
{
	Stack< double >doubleStack(5);
	double doubleValue = 1.1;

	cout<<"pushing elements onto doubleStack :\n";

	while(doubleStack.push(doubleValue))
	{
	
		cout<<doubleValue<<" ";
		doubleValue += 1.1;
	
	}

	cout<<"\nStack is full. can't push "<<doubleValue
		<<"\n\nPoping elements from doubleStack\n";

	while(doubleStack.pop(doubleValue))
		cout<<doubleValue<<" ";

	cout<<"\nStack is empty. Cannot pop";

	Stack< int >intStack;
	int intValue = 1;
	cout<<"pushing elements onto intStack :\n";

	while(intStack.push(intValue))
	{
	
		cout<<intValue<<" ";
		++intValue;
	}

	cout<<"\nStack is full. can't push "<<intValue
		<<"\n\nPoping elements from intStack\n";
	while(intStack.pop(intValue))
		cout<<intValue<<" ";


	cout<<"\nStack is empty. Cannot pop";

	


	return 0;	
}
/*向栈中添加元素,并且出栈,很不错的程序。*/


执行的结果:


通过以上的例子可以看出模板简化了程序,使程序更加清晰。

学习c++其实还是蛮痛苦的,推荐一本好书《范磊c++》,很适合入门者。

谢谢!







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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值