C++中的类模板详细讲述

一、类模板定义及实例化

1. 定义一个类模板:

template<class 模板参数表>

class 类名{

// 类定义......

};

其中,template 是声明类模板的关键字,表示声明一个模板,模板参数可以是一个,也可以是多个,可以是类型参数 ,也可以是非类型参数。类型参数由关键字class或typename及其后面的标识符构成。非类型参数由一个普通参数构成,代表模板定义中的一个常量。

例:

1 template<class type,int width>
2 
3 //type为类型参数,width为非类型参数
4 
5 class Graphics;

注意:

(1)如果在全局域中声明了与模板参数同名的变量,则该变量被隐藏掉。

(2)模板参数名不能被当作类模板定义中类成员的名字。

(3)同一个模板参数名在模板参数表中只能出现一次。

(4)在不同的类模板或声明中,模板参数名可以被重复使用。

typedef string type;

template<class type,int width>

class Graphics

{

type node;//node不是string类型

typedef double type;//错误:成员名不能与模板参数type同名

};

template<class type,class type>//错误:重复使用名为type的参数

class Rect;

template<class type> //参数名”type”在不同模板间可以重复使用

class Round;

(5)在类模板的前向声明和定义中,模板参数的名字可以不同。

// 所有三个 Image 声明都引用同一个类模板的声明

template <class T> class Image;

template <class U> class Image;

// 模板的真正定义

template <class Type>

class Image { //模板定义中只能引用名字”Type”,不能引用名字”T”和”U” };

(6)类模板参数可以有缺省实参,给参数提供缺省实参的顺序是先右后左。

template <class type, int size = 1024>

class Image;

template <class type=double, int size >

class Image;

(7)类模板名可以被用作一个类型指示符。当一个类模板名被用作另一个模板定义中的类型指示符时,必须指定完整的实参表

template<class type>

class Graphics

{

Graphics *next;//在类模板自己的定义中不需指定完整模板参数表

};

template <calss type>

void show(Graphics<type> &g)

{

Graphics<type> *pg=&g;//必须指定完整的模板参数表

}

猜你喜欢

转载自blog.csdn.net/imgsq/article/details/58606705
今日推荐