C++入门经典 笔记 (第二十三章)创建模板

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lishanlu136/article/details/48262125

上一章是通过一个案例分析来讲述怎样做面向对象分析和设计,于是上一章我就没写出来,因为其中要讲的细节太多了。这一章,讲述了模板类的创建,模板可以让你创建通用类,通过将类型作为参数传递给模板,可创建其实例。

模板的定义

如要声明模板类List,可使用关键字template,如下所示:

template  <class T> // declare  the  template  and  the  parameter

class List                   //the  class  being  parameterized

{

public:

            List();

            //  full  class  declaration  here

};

所有模板类的声明和定义都以关键字template打头,接下来是模板的参数,它们随模板实例而异。在这个例子中,使用了关键字class和标识符T。关键字class表明这个参数为类型;在模板定义的其他地方,都将使用标识符T来表示参数化类型。在这个类的一个实例中,可能使用int替换所有T,而在另一个实例中,可能使用Cat类替换所有T。

猜你喜欢

转载自blog.csdn.net/lishanlu136/article/details/48262125