使用模板的目的:
模板是C++标准中相当重要的一部分,它是通用编程成为现实的理想方法。模板还有在编译时被解释的特点。模板是对迅速解决复杂问题有效手段,特别是标准模板类库
使用模板的优缺点:
(1) 优点 : 1)编写一个模板,就可以在实例化的时候 由一个模板解决不同类型数据所产生的相同问题;比如说排序问题,你可以给int 数据排序和cha类型数据排序,没有引入类模板,就需要编写两次排序函数,而引入类模板之后,就可以在实例化的时候,根据不同的数据类型实例化排序方法,做到一模板半多用的作用,即多态。
2)实现了代码的重用,节约了程序员时间和精力,这也是出现标准库的原因
(2) 缺点:1)模板的数据类型只能在编译时才能被确定。因此,所有用基于模板算法的实现必须包含在整个设计的头文件中。
2)由于模板只是最近加入C++标准中,所以有些C++编译器还不支持模板,当使用这些编译器时编译含有模板的代码时就会发生不兼容问题。
关于模板的例子
(1)函数模版
#include
using namespace std;
template
T maximum(const T n1,const T n2)
{
if(n1>n2)
return n1;
else
return n2;
}
int main()
{
charc1='a',c2='b';
inti1=1,i2=2;
double f1=2.5,f2=3.5;
cout<
(2)类模板
文件1: stack.h
#if !defined SATACK_T_H
#define SATACK_T_H
template
class stack
{
public:
stack( int n = 10 );
~stack();
bool pop(T & data_item);
bool push(const T & data_item);
inline int number_stacked()const;
inline int stack_size() const;
private:
int max_size;
int top;
T* data;
};
template
stack::stack(int n)
{
max_size = n;
top = -1;
data = new T[n];
}
template
stack::~stack( )
{
delete [] data;
}
template
bool stack::push(const T &data_item )
{
if( top < max_size - 1)
{
data[++ top ] = data_item ;
return true;
}
else
return false;
}
template
bool stack::pop(T & data_item)
{
if( top > -1 )
{
data_item = data [top -- ];
return true;
}
else
return false;
}
template
int stack::number_stacked() const
{
return top+1;
}
template
int stack::stack_size() const
{
return max_size;
}
#endif
在这里需要注意一个问题:
引用类模板时必须包含它的形参列表,这就是成员函数使用stack《T》而不是stack的原因。如果堆栈类不是模板,仅需要使用stack。
文件2:
Stack1.cpp
#include
#include"stack.h"
using namespace std;
int main()
{
stack i_stack;
stack c_stack(5);
int i,n,int_data;
char char_data;
bool success;
c_stack.push('a');
c_stack.push('b');
c_stack.push('c');
n= i_stack.stack_size();
for( i = 0; i < n ; i ++ )
{ i_stack.push(i); }
cout<<"character stack data: "<