笔记【数据结构】模板
模板:对具有相同特性的函数或类的再抽象。模板是一种参数化的多态工具。
模板分为:函数模板,类模板
函数模板的定义:
例:求绝对值功能的函数模板定义
#include<iostream.h>
template<typename T> //模板定义,T为模板参数
T abs(T a) { //定义函数模板
return
a<0?-a:a;
}
void main(){
int x=-12;
double y=12.5;
cout<<abs(x)<<endl;
cout<<abs(y)<<endl;
}
求最大值功能的函数模板的定义
#include <iostream.h>
template <class T>
T Max(T x,T y){
return (x>y)?x:y;
}
int main(){
int x1,y1;
float x2,y2;
dcout<<"请输入2个整型数据,用空格分隔:"<<endl;
cin>>x1>>y1;
cout<<"The max of x1,y1
is:"<<Max(x1,y1)<<endl;
//T为int
cout<<"请输入2个实型数据,用空格分隔:"<<endl;
cin>>x2>>y2;
cout<<"The max of x2,y2
is:"<<Max(x2,y2)<<endl;
//T为float
cout<<"请输入2个双精度数据,用空格分隔:"<<endl;
cin>>x3>>y3;
cout<<“The max of x3,y3 is:”<<Max(x3,y3)<<endl; //T为 double
return 0;
ouble x3,y3;
}
template是模板定义的关键字。
<模板形参表>中包含一个或多个用逗号分开的模板形式参数,每一项均由关键字class或typename引导一个由用户命名的标识符,此标识符为模板参数(用来进行类型传递)
模板参数表示一种数据类型,可以是基本数据类型或类类型。该数据类型在发生实际函数调用时将被实例化,即用调用处的实际数据类型替代它。
template <模板形参表>
class 类模板名
{
成员的声明;
}
#include
using namespace std;
template //typename或class
class Square //类模板定义
{
T x;
public:
Square(T xx):x(xx){ }
T fun(){return x*x;}
};
类模板中的成员函数的定义,若放在类模板的定义之中,则与类的成员函数的定义方法相同;
若在类模板之外定义,则成员函数的定义格式如下:
template<模板形参表>
返回值类型
类模板名<形参名表>::成员函数名(参数表)
{
成员函数体
}
#include <iostream>
using namespace std;
template <typename T> //typename或class
class Square{ //类模板定义
T x;
public:
Square(T xx):x(xx){}
T fun(){return x*x;}
};
int main() {
Square <int>
inta(15); //类的实例化
Square <float>
floata(16.5);
Square <double>
doublea(15.55);
cout<<"square of int
data:"<<inta.fun()<<endl;
cout<<"square of float
data:"<<floata.fun()<<endl;
cout<<"square of double
data:"<<doublea.fun()<<endl;
}
抽象数据类型长方形的定义
template <typename T>
class Rectangle{
private:
T length,width;
public:
Rectangle(T l, T w );
~Rectangle( );
T getLength( );
T getWidth( );
T circumference( );
T area( );
};
对于成员函数在类外定义的时候,有何变化:
double Rectangle::circumference( )
{
//普通类的成员函数在类外定义
return 2lengthwidth;
}
template
T Rectangle::circumference( )
{
//类模板的成员函数在类外的定义
return 2lengthwidth;
}
类模板实例化的格式如下:
类模板名
<实际类型>
定义模板类的对象的格式如下:
类模板名 <实际类型> 对象名(实参表);
#include <iostream>
using namespace std;
template <typename T> //typename或class
class Square { //类模板定义
T x;
public:
Square(T xx):x(xx){}
T fun(){return x*x;}
};
int main() {
Square <int> inta(15);
Square <float>
floata(16.5);
Square <double>
doublea(15.55);
cout<<"square of int
data:"<<inta.fun()<<endl;
cout<<"square of float
data:"<<floata.fun()<<endl;
cout<<"square of
double
data:"<<doublea.fun()<<endl;
return 0;
}
}
,,,
,,,