0%

C++中的类模板

使用template关键字不但可以定义函数模板,也可以定义类模板,类模板代表一族类,是用来描述通用数据或处理方法的机制,它使类中的一些数据成员和成员函数的参数或返回值可以取任意的数据类型。类模板可以说是用类生成类,减少了类的定义数量。

类模板的定义与声明

类模板的定义形式:

1
2
3
template <类型形式及参数> class 类模板名{
//类模板体
}

也可以声明类模板分成template部分和类部分:

1
2
3
4
template <类型形式及参数> 
class 类模板名{
//类模板体
}

template为关键字,表示定义一个模板。
<>表示模板参数,模板参数有两种,是模板类型参数、模板非类型参数。模板类型参数使用关键字class或typedef开始,后面跟一个合法类型名。模板非类型参数与普通参数定义相同,通常是一个常数。可以不使用模板非类型参数。

模板类型参数的综合应用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include<iostream>
using namespace std;
/*
通过<>把int、double两种数据类型分别传送到类
模板type1、type2进行类的创建、构造函数、show函数的运算输出。
*/
template <class type1,class type2>
class test
{
public:
type1 x;
type2 y;
test(type1 a,type2 b)
{
x=a;
y=b;
}
void show()
{
cout<<x<<" "<<y;
}
};

int main()
{
int a=4;
int b=5;
test<int,int>name(a,b); //类模板的调用
name.show();
return 0;
}

稍作解释:

1、首先是声明一个类模板 template < class type >,type表示参数的数据类型。
2、然后是定义类模板的具体实现方法
3、最后是类模板的调用C< int >p(a);将<>里的数据类型int传送到类模板中,int将代替类模板中的type进行构造函数及类中一系列自定义函数的运行,最终p.show();输出结果。

只需要把类的对象的数据类型传送到模板中,模板将自动生成符合要求的类。 这样我们就避免了因为数据类型各种各样,而频繁创建类的问题。
所以,定义类模板的优点就是适应各种类型对象的计算及输入输出。

默认模板类型参数的应用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include<iostream>
using namespace std;
template <class type1,class type2=int>//区别点
class test
{
public:
type1 x;
type2 y;
test(type1 a,type2 b)
{
x=a,y=b;
}
void show()
{
cout<<x<<" "<<y<<endl;
}
};
int main(){

int a=2020;
double b=1111.22;
test<int,double>name1(a,b);//区别点
name1.show();
test<int>name2(a,b);//区别点
name2.show();

return 0;
}

与上题不同之处在于,在定义类模板时template <class type1,class type2=int>给type增加了一个默认数据类型int,所以在调用类模板创建类对象test< int >name2(a,b);时,name2只规定了type1的数据类型,那么type2将采取默认值int,输出类型也将为int。

模板非类型参数的入门应用

将模板非类型参数应用到int、double类型的输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<iostream>
using namespace std;
template <class type1,class type2,int n=1>//区别点
class test
{
public:
type1 x;
type2 y;
test(type1 a,type2 b)
{
x=a,y=b;
}
void show()
{
cout<<x+n<<" "<<y+n<<endl;
}
};
int main()
{
int a=2020;
double b=1111.22;
test<int,double>name(a,b);//区别点
name.show();
return 0;
}

在定义类模板template <class type1,class type2,int n=1>时加入了模板非类型参数n参与运算。