一、为什么要用类模板
1、类模板用于实现类所需数据的类型参数化
2、类模板在表示如数组、表、图等数据结构显得特别重要,这些数据结构的表示和算法不受所包含的元素类型的影响
二、类模板基本语法
1、类模板创建对象一定要显示调用
#include <iostream>
using namespace std;
template<typename T,typename U>
class Test
{
private:
T a;
U b;
int c;
public:
Test(T a,U b)
{
this->c = c;
this->a = a;
this->b = b;
}
void show()
{
cout << a << " " << b << endl;
}
};
int main()
{
Test<int,char> t(0,1,'a'); //类模板创建对象一定要显示调用
t.show();
return 0;
}
2、继承中的类模板语法
1、模板类派生普通类
需要将基类虚拟类型实际化
22 class Child : public Parent<int> //模板类派生普通类 需要将基类虚拟类型实例化
23 {
24 public:
25 Child(int a) : Parent(a)
26 {
27
28 }
29
30 void show()
31 {
32 cout << a << endl;
33 }
34 };
2、模板类派生模板类
1、要继承基类的虚拟类型
Child2(T a,U b) :Parent<T>(a) //对象初始化链表要带上参数类型
template <typename T,typename U>
class Child2 : public Parent<T> //模板类派生模板类
{
private:
U b;
public:
Child2(T a,U b) :Parent<T>(a)
{
this->b = b;
}
void show()
{
cout << this->a << " "<< b << endl;
}
};
3、类模板相关说明
1、函数在类的内部声明,在类的外部实现
Test<T>::Test(T a) //表示Test是模板类作用域 不是;普通类
2、一个文件写
#include <iostream>
using namespace std;
template <typename T>
class Test
{
private:
T a;
public:
Test(T a);
void show();
~Test();
};
template <typename T>
Test<T>::Test(T a) //表示Test是模板类 不是;普通类
{
this->a = a;
}
template <typename T>
void Test<T>::show()
{
cout << a << endl;
}
template <typename T>
Test<T>::~Test()
{
cout << "Test析构函数" << endl;
}
int main()
{
Test<int> a(1);
a.show();
return 0;
}
3、多文件编写(写在一个文件 或 .hpp用作头文件展开)
实现方法
1、类模板的成员函数功能的定义和使用要在一个文件中,实现两次编译
2、将类模板成员函数功能定义的文件修改为.hpp结尾的文件。(将文件修改为hpp)
4、类模板中的static关键字
1、相同类型的对象共享static修饰的变量
实例int 和 实例char 不共享static变量
实例int 和 实例int 共享。
每个模板类有自己的类模板数据成员,该模板类的所有对象共享一个static数据成员
#include <iostream>
using namespace std;
template <typename T>
class Test
{
private:
T a;
public:
static int count;
public:
Test( T a)
{
this->a = a;
count++;
}
};
template <typename T>
int Test<T>::count = 0;
int main()
{
Test<int> t1(1);
Test<int> t2(1);
cout << t1.count << endl;
return 0;
}