14.面向对象-类模板(template<typename xx>)

一、为什么要用类模板

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值