首页 技术 正文
技术 2022年11月8日
0 收藏 578 点赞 2,070 浏览 1792 个字

具体模板类作用这边就不细说了,下面主要是描述下模板类的使用方法以及注意的一些东西。

#include <iostream>
using namespace std;
template <typename numtype>
//定义类模板
class Compare
{
public :
Compare(numtype a,numtype b)
{x=a;y=b;}
numtype max( )
{return (x>y)?x:y;}
numtype min( )
{return (x<y)?x:y;}
private :
numtype x,y;
};
int main( )
{
Compare<int > cmp1(,);//定义对象cmp1,用于两个整数的比较
cout<<cmp1.max( )<<″ is the Maximum of two integer numbers.″<<endl;
cout<<cmp1.min( )<<″ is the Minimum of two integer numbers.″<<endl<<endl;
Compare<float > cmp2(45.78,93.6); //定义对象cmp2,用于两个浮点数的比较
cout<<cmp2.max( )<<″ is the Maximum of two float numbers.″<<endl;
cout<<cmp2.min( )<<″ is the Minimum of two float numbers.″<<endl<<endl;
Compare<char> cmp3(′a′,′A′); //定义对象cmp3,用于两个字符的比较
cout<<cmp3.max( )<<″ is the Maximum of two characters.″<<endl;
cout<<cmp3.min( )<<″ is the Minimum of two characters.″<<endl;
return ;
}

使用方法

1)先写出一个实际的类。由于其语义明确,含义清楚,一般不会出错。

2)将此类中准备改变的类型名(如int要改变为float或char)改用一个自己指定的虚拟类型名(如上例中的numtype)。

3)在类声明前面加入一行,格式为
          template <typename 虚拟类型参数>,如
          template <typename numtype> //注意本行末尾无分号
          class Compare
          {…}; //类体

4)用类模板定义对象时用以下形式:
          类模板名<实际类型名> 对象名;
          类模板名<实际类型名> 对象名(实参表列);
          如
          Compare<int> cmp;
          Compare<int> cmp(3,7);

说明:Compare是类模板名,而不是一个具体的类,类模板体中的类型numtype并不是一个实际的类型,只是一个虚拟的类型,无法用它去定义对象。
必须用实际类型名去取代虚拟的类型,具体的做法是:
       Compare <int> cmp(4,7);
      即在类模板名之后在尖括号内指定实际的类型名,在进行编译时,编译系统就用int取代类模板中的类型参数numtype,这样就把类模板具体化了,或者说实例化了。

5) 如果在类模板外定义成员函数,应写成类模板形式:
         template <class 虚拟类型参数>
         函数类型 类模板名<虚拟类型参数>::成员函数名(函数形参表列) {…}

eg:

template <nametype numtype>
           numtype Compare<numtype>::max( )
           {{return (x>y)?x:y;}

补充说明

1)类模板的类型参数可以有一个或多个,每个类型前面都必须加class,如
          template <class T1,class T2>
          class someclass
          {…};
          在定义对象时分别代入实际的类型名,如
          someclass<int,double> obj;

2)和使用类一样,使用类模板时要注意其作用域,只能在其有效作用域内用它定义对象。

参考:http://see.xidian.edu.cn/cpp/biancheng/view/213.html

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,488
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,903
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,737
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,489
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,128
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,290