栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

2021-11-15 C++模板的相关知识和代码分析

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

2021-11-15 C++模板的相关知识和代码分析

1 模板 1.1模板的概念

模板就是建立通用的模具,大大提高复用性!

1.2函数模板

函数模板作用:
建立一个通用函数,其函数返回值类型和形参类型可以不具体制定,用一个虚拟的类型来代表。
语法:
1 template
2函数声明或定义
解释:
template —声明创建模板
typename —表面其后面的符号是一种数据类型,可以用class代替T —通用的数据类型,名称可以替换,通常为大写字母

1.2.1 函数模板语法
#include
using namespace std;
// c++另一种编程思想称为泛型编程,主要技术就是模板
// c++提供两种模板机制::函数模板和类模板
//函数模板作用:建立一个通用函数,其函数返回值类型和形参类型可以不具体指定,用一个虚拟的类型来代表。

//两个整形交换函数
void swapint(int &a, int &b)
{
	int temp = a;
	a = b;
	b = temp;
}
//交换两个浮点型函数
void swapdouble(double& a, double& b)
{
	double temp = a;
	a = b;
	b = temp;
}

//函数模板
template   //声明一个模板,告诉编译器后面代码中紧跟着的T不要报错,T是一个通用数据类型
void myswap(T& a, T& b)
{
	T temp = a;
	a = b;
	b = temp;
}

void test01()
{
	int a = 10;
	int b = 20;
	//swapint(a, b);
	//用函数模板交换
	//两种方式使用函数模板
	//1. 自动类型推导
	//myswap(a, b);
	
	//2. 显示指定类型
	myswap(a, b);

	cout << "a=" << a << endl;
	cout << "b=" << b << endl;

	//double c = 10.1;
	//double d = 20.2;
	//swapdouble(c, d);
	//cout << "c=" << c << endl;
	//cout << "d=" << d << endl;
}

int main() {
	test01();
	system("pause");
	return 0;
}
1.2.2 函数模板注意事项

注意事项:
自动类型推导,必须推导出一致的数据类型T,才可以使用模板
必须要确定出T的数据类型,才可以使用

#include
using namespace std;
//函数模板注意事项
template   //typename可以替换成class
void myswap(T& a, T& b)
{
	T temp = a;
	a = b;
	b = temp;
}
//1.自动类型推导,必须推导出一致的数据类型T才可以使用
void test01()
{
	int a = 10;
	int b = 20;
	string c = "c";

	myswap(a, b);  //正确
	//myswap(a, c);  //错误  ,推导不出一致的T类型

	cout << "a=" << a << endl;
	cout << "b=" << b << endl;
}

//2.模板必须要确定出T的数据类型,才可以使用 
template   //typename可以替换成class
void func()
{
	cout <<"func调用" << endl; //没用到T
}
void test02()
{
	func();  //错误!必须确定T的类型
	func();  //必须确定T的类型
}
int main() {
	test02();
	system("pause");
	return 0;
}
1.2.3 函数模板案例

案例描述:
利用函数模板封装一个排序的函数,可以对不同数据类型数组进行排序·
排序规则从大到小,排序算法为选择排序
分别利用char数组和int数组进行测试

#include
using namespace std;
//案例描述
//利用函数模板封装一个排序的函数,可以对不同数据类型数组进行排序
//排序规则从大到小,排序算法为选择排序
//分别利用char数组和int数组进行测试

//实现一个通用的 对数组进行排序的函数

//交换函数模板
template 
void myswap(T& a, T& b)
{
	T temp = a;
	a = b;
	b = temp;
}
//排序算法
template 
void mysort(T arr[], int len)
{
	for (int i = 0; i < len; i++)
	{
		int max = i; //设定最大值的下标
		for (int j = 1 + i; j < len; j++)
		{
			//认定的最大值 比  遍历出的数值 要小, 说明  j下标的元素才是最大值
			if (arr[max] < arr[j])
			{
				max = j;  //更新最大值下标
			}
		}
		if (max != i)
		{
			//交换max和i元素
			myswap(arr[max], arr[i]);
		}
	}
}

//提供打印数组的模板
template 
void printarray(T arr[], int len)
{
	for (int i = 0; i < len; i++)
	{
		cout << arr[i] <<"  ";
	}
	cout << endl;
}

void test01()
{
	//测试char数组
	char chararr[] = "badcfe";
	int num = sizeof(chararr) / sizeof(char);
	mysort(chararr, num);
	printarray(chararr, num);
}

void test02()
{
	//测试int数组
	int chararr[] = {22,33,1,2,5,7,3,1,55,22,11,555,22222,33};
	int num = sizeof(chararr) / sizeof(int);
	mysort(chararr, num);
	printarray(chararr, num);
}

int main() {
	test02();
	system("pause");
	return 0;
}
1.2.4 普通函数与函数模板的区别

普通函数与函数模板区别:
普通函数调用时可以发生自动类型转换(隐式类型转换)
函数模板调用时,如果利用自动类型推导,不会发生隐式类型转换
如果利用显示指定类型的方式,可以发生隐式类型转换

#include
using namespace std;
//普通函数和函数模板的区别

//1. 普通函数调用可以发生隐式类型转换
//2. 函数模板 用自动类型推导  不可以发生隐式类型转换
//3. 函数模板 用显示指定类型  可以发生隐式类型转换

//普通函数
int myadd01(int a, int b)
{
	return a + b;
}

//函数模板
template 
T myadd02(T a, T b)
{
	return a + b;
}

void test01()
{
	int a = 10;
	int b = 20;
	char c = 'c';  //普通函数调用可以发生隐式类型转换
	cout << myadd01(a,c) <(a,c) < 
1.2.5 普通函数与函数模板的调用规则 
#include
using namespace std;

//1. 如果函数模板和普通函数都可以调用,优先调用普通函数
//2. 可以通过空模板参数列表  强制调用 函数模板
//3. 函数模板可以发生函数重载
//4. 如果函数模板可以产生更好的匹配,优先调用函数模板

void myprint(int a, int b);
//{
//	cout << "调用的普通函数" << endl;
//}

template 
void myprint(T a, T b)
{
	cout <<"调用的函数模板" << endl;
}

template 
void myprint(T a, T b,T c)
{
	cout << "调用重载的函数模板" << endl;
}

void test01()
{
	int a = 10;
	int b = 20;

	//1. 如果函数模板和普通函数都可以调用,优先调用普通函数
	//myprint(a, b); //调哪个呢??两个函数,名字都一样!

	//2. 可以通过空模板参数列表  强制调用 函数模板
	myprint<>(a, b);

	//3. 函数模板可以发生函数重载
	myprint(a, b, 100);

	//4. 如果函数模板可以产生更好的匹配,优先调用函数模板
	char c1 = 'a';
	char c2 = 'b';     //字符类型一致,函数模板也可以调用
	myprint(c1, c2);  //普通函数需要隐式类型转换两步走,而函数模板只需要转换成T
}
int main() {
	test01();
	//总结:既然提供了函数模板,就不要用普通函数了,以免出现二义性。
	system("pause");
	return 0;
}
1.2.6 模板的局限性


因此C++为了解决这种问题,提供模板的重载,可以为这些特定的类型提供具体化的模板

#include
using namespace std;

//模板不是万能的,有些特定数据类型,需要用具体化方式做特殊实现
class person
{
public:
	person(string name, int age)
	{
		this->m_name = name;
		this->m_age = age;
	}
	string m_name;
	int m_age;
};
//对比两个数据是否相等
template 
bool mycompare(T& a, T& b)
{
	if (a == b)
	{
		return true;
	}
	else
	{
		return false;
	}
}

//重载模板
//利用具体化person的版本实现代码,具体化优先调用
template<> bool mycompare(person& p1, person& p2)
{
	if (p1.m_name == p2.m_name && p1.m_age == p2.m_age)
	{
		return true;
	}
	else
	{
		return false;
	}
}

void test01()
{
	int a = 10;
	int b = 20;
	bool ret = mycompare(a, b);
	if (ret)
	{
		cout << "a==b" << endl;
	}
	else
	{
		cout << "a!=b" << endl;
	}
}

void test02()
{
	person p1("tom", 10);
	person p2("tom", 10);

	bool ret = mycompare(p1, p2);
	if (ret)
	{
		cout << "a==b" << endl;
	}
	else
	{
		cout << "a!=b" << endl;
	}
}

int main() {
	test02();
	system("pause");
	return 0;
}
1.3 类模板

类模板作用:
·建立一个通用类,类中的成员数据类型可以不具体制定,用一个虚拟的类型来代表。
语法:
template
解释:
template —声明创建模板
typename —表面其后面的符号是一种数据类型,可以用class代替T —通用的数据类型,名称可以替换,通常为大写字母

1.3.1 类模板语法
#include
using namespace std;
//
template 
class person
{
public:
	person(Nametype name, Agetype age)
	{
		this->m_name = name;
		this->m_age = age;
	}

	void showperson()
	{
		cout << "name: " << this->m_name << "nage: " << this->m_age;
		cout<< endl;
	}
	Nametype m_name;
	Agetype m_age;
};

void test01()
{
	person p1("穆久涛", 999);
	p1.showperson();
}

int main() {
	test01();
	system("pause");
	return 0;
}
1.3.2 类模板与函数模板区别

类模板与函数模板区别主要有两点:
1.类模板没有自动类型推导的使用方式
2.类模板在模板参数列表中可以有默认参数

#include
using namespace std;
//this是实例对象的指针
//类模板没有自动类型推导的使用方式
//类模板在模板参数列表中可以有默认参数

template 
class person
{
public:
	person(nametype name, agetype age)
	{
		this->m_name = name;
		this->m_age = age;
	}
	void showperson()
	{
		cout << "name: " << this->m_name << "age= " << this->m_age << endl;
	}
	
	nametype m_name;
	agetype m_age;
};
//1 类模板没有自动类型推导的使用方式
void test01()
{
	//person p("孙悟空", 1000);  错误的,无法自动类型推导
	personp("孙悟空", 1000);

	p.showperson();
}
//2 类模板在模板参数列表中可以有默认参数
void test02()
{
	personp("猪八戒", 99);
	p.showperson();
}
int main() {
	test01();
	system("pause");
	return 0;
}
1.3.3 类模板中成员函数创建时机

类模板中成员函数和普通类中成员函数创建时机是有区别的:
普通类中的成员函数—开始就可以创建
类模板中的成员函数在调用时才创建

#include
using namespace std;
//类模板中成员函数的创建时机
//类模板中成员函数在调用时才去创建

class person1
{
public:
	void showperson1()
	{
		cout << "person1 show" << endl;
	}
};

class person2
{
public:
	void showperson2()
	{
		cout << "person2 show" << endl;
	}
};

template 
class myclass
{
public:
	T obj;
	//类模板中的成员函数
	void func1()
	{
		obj.showperson1();
	}
	//类模板中的成员函数
	void func2()
	{
		obj.showperson2();
	}
};

void test01()
{
	myclass m;
	m.func1();
	//m.func2()   编译时候会出错。说明函数调用时才会去创建成员函数
}
int main() {
	test01();
	system("pause");
	return 0;
}
1.3.4 类模板对象做函数参数

学习目标:
类模板实例化出的对象,向函数传参的方式
—共有三种传入方式:
1.指定传入的类型—直接显示对象的数据类型
⒉参数模板化—将对象中的参数变为模板进行传递
3.整个类模板化—将这个对象类型模板化进行传递

#include
using namespace std;

//类模板对象作函数参数
template 
class person
{
public:
	person(T1 name, T2 age)
	{
		this->m_name = name;
		this->m_age = age;
	}
	void showperson()
	{
		cout << "name: " << this->m_name << "   age= " << this->m_age << endl;
	}

	T1 m_name;
	T2 m_age;
};
//1 指定传入类型  直接显示对象的数据类型
void printperson1(person&p)  //将模板的参数列表也传进去
{
	p.showperson();
}
void test01()
{
	personp("孙悟空", 1000);
	printperson1(p);
}

//2 参数模板化   将对象中的参数变为模板进行传递
template
void printperson2(person&p)
{
	p.showperson();
	cout << "T1类型为" << typeid(T1).name() << endl;
	cout << "T2类型为" << typeid(T2).name() << endl;
}
void test02()
{
	personp("猪八戒", 3000);
	printperson2(p);
}

//3 整个类模板化   将这个对象类型 模板化进行传递
template 
void printperson3(T &p)
{
	p.showperson();
	cout << "T类型为" << typeid(T).name() << endl;
}
void test03()
{
	personp("唐僧", 30);
	printperson3(p);
}

int main() {
	test03();
	system("pause");
	return 0;
}
1.3.5 类模板与继承

当类模板碰到继承时,需要注意一下几点:
·当子类继承的父类是一个类模板时,子类在声明的时候,要指定出父类中T的类型·如果不指定,编译器无法给子类分配内存
·如果想灵活指定出父类中T的类型,子类也需变为类模板

#include
using namespace std;
//类模板碰到继承时,需要注意一下几点:
//当子类继承的父类是一个类模板时,子类在声明的时候,要指出父类中T的类型
//如果不指定,编译器无法给子类分配内存
//如果想要灵活指出父类中T的类型,子类也需要变为类模板

template
class base
{
public:
	T m;
};

//class son :public base  //错误的,必须要知道父类中的T的数据类型,才能继承给子类
class son :public base
{

};

void test01()
{
	son s1;
}

//如果想要灵活指定父类中的T的类型,子类也需要变成类模板   儿子决定爸爸的类型
template 
class son2 :public base
{ 
public:
	son2()
	{
		cout << "T1类型为" << typeid(T1).name() << endl;
		cout << "T2类型为" << typeid(T2).name() << endl;
	}
	T1 obj;
};

void test02()
{
	son2s2;
}
int main() {
	test02();
	system("pause");
	return 0;
}
1.3.6 类模板成员函数类外实现
#include
using namespace std;
//

template
class person
{
public:
	person(T1 name, T2 age);   //类内声明
	//{
	//	this->m_name = name;
	//	this->m_age = age;
	//}
	void showperson();
	//{
	//	cout << "name: " << this->m_name << "age= " << this->m_age << endl;
	//}
	T1 m_name;
	T2 m_age;

};

//构造函数类外实现
template
person::person(T1 name, T2 age)
{
	this->m_name = name;
	this->m_age = age;
}

//成员函数的类外实现
template
void person::showperson()
{
	cout << "name: " << this->m_name << "age= " << this->m_age << endl;
}

void test01()
{
	personp("tom", 20);
	p.showperson();
}
int main() {
	test01();
	system("pause");
	return 0;
}
1.3.7 类模板分文件编写

在这里说两句。
一般我们分文件编写,都是.h文件中声明类,.cpp文件写具体函数,但是这个方法在类模板中不可行,因为类模板调用时机是在程序运行过程中的,所以我们可以直接把.h和.cpp的两个文件合到一块,后缀改成.hpp文件就可以了。。。。

#include
using namespace std;

//第一种解决方式,直接包含 源文件
#include "180 person.cpp"  //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

第二种解决方式,将.h和.cpp中的内容写到一起,将后缀名改为.hpp文件

//类模板分文件编写问题以及解决
//template
//class person
//{
//public:
//	person(T1 name, T2 age);   //类内声明
//	void showperson();
//
//	T1 m_name;
//	T2 m_age;
//};

构造函数类外实现
//template
//person::person(T1 name, T2 age)
//{
//	this->m_name = name;
//	this->m_age = age;
//}
//
成员函数的类外实现
//template
//void person::showperson()
//{
//	cout << "name: " << this->m_name << "age= " << this->m_age << endl;
//}

void test01()
{
	Personp("tom", 20);
	p.showperson();
}
int main() {
	test01();

	system("pause");
	return 0;
}
1.3.8 类模板与友元

**学习目标:**掌握类模板配合友元函数的类内和类外实现
全局函数类内实现-直接在类内声明友元即可
全局函数类外实现–需要提前让编译器知道全局函数的存在

#include
using namespace std;

//通过全局函数,打印person信息
//全局函数类内实现,直接在类内声明友元即可
//全局函数类外实现,需要提前让编译器知道全局函数的存在

//提前让编译器知道person类的存在
template
class person;

//类外实现
template
void printperson2(person p)
{
	cout << "类外实现——name: " << this->m_name << "age= " << this->m_age << endl;
}

template
class person
{
public:
	//全局函数类内实现
	friend void printperson(personp)  //告诉编译器,后面这个全局函数是我的友元,然后编译器去找这个函数的实现,这里比较特殊,我直接类内给实现
	{
		cout << "name: " << this->m_name << "age= " << this->m_age << endl;
	}
	//全局函数类外实现
	//加一个空模板的参数列表,让普通函数变成模板函数
	//如果全局函数是类外实现,需要让编译器提前知道这个函数的存在  1.直接把类外实现的函数放到最上面
	friend void printperson2<>(person p);         

	person(T1 name, T2 age)   //类内声明
	{
		this->m_name = name;
		this->m_age = age;
	}
private:
	T1 m_name;
	T2 m_age;
};


//1. 全局函数类内实现
void test01()
{
	personp("tom", 20);
	printperson(p);
}

//2. 全局函数类外实现
void test02()
{
	personp("jerry", 20);
	printperson2(p);
}

int main() {
	//test01();
	test02();
	system("pause");
	return 0;
}
1.3.9 类模板案例

实现一个通用的数组类,要求如下:

可以对内置数据类型和自定义数据类型的数据进行存储
将数组中的数据存储到堆区
构造函数中可以传入数组的容量
提供对应的拷贝构造函数以及operator=防止浅拷贝问题
提供尾插法和尾删法对数组的数据进行增加和删除
可以通过下标的方式访问数组中的元素
可以获取数组中当前元素的个数和数组的容量

.hpp文件中的内容
//自己通用的数组类
#pragma once
#include 
using namespace  std;
#include 

template
class myarray
{
public:
	//有参构造 参数 容量
	myarray(int capacity)
	{
		cout << "myarray 的 有参调用" << endl;
		this->m_capacity = capacity;
		this->m_size = 0;
		this->paddress = new T [this->m_capacity];
	}

	//析构函数,堆区开辟了这个数据,手动开辟手动释放
	~myarray()
	{
		cout << "myarray 的 析构函数调用" << endl;
		if (this->paddress != NULL)
		{
			delete[] this->paddress;
			this->paddress;
		}
	}

	//拷贝构造函数,需要自己写,因为为了防止浅拷贝
	myarray(const myarray & arr)
	{
		cout << "myarray 的 拷贝构造调用" << endl;
		this->m_capacity = arr.m_capacity;
		this->m_size = arr.m_size;
		//this->paddress = arr.paddress;  //指针不能这样赋值,浅拷贝的问题导致重复释放

		this->paddress = new T[arr.m_capacity];  //深拷贝,从新在堆区开辟空间,指针维护他

		//将arr中的数据拷贝过来
		for (int i = 0; i < this->m_size; i++)
		{
			this->paddress[i] = arr.paddress[i];
		}
	}


	//operator=防止浅拷贝问题  a=b=c等号做赋值传递,连着传递要做引用的方式
	myarray& operator=(const myarray& arr)
	{
		cout << "myarray 的 operator调用" << endl;
		//先判断原来堆区是否有数据,如果有先释放
		if (this->paddress != NULL)
		{
			delete[] this->paddress;
			this->paddress = NULL;
			this->m_capacity = 0;
			this->m_size = 0;
			cout << "赋值堆区释放" << endl;
		}

		//深拷贝
		this->m_capacity = arr.m_capacity;
		this->m_size = arr.m_size;
		this->paddress = new T[arr.m_capacity];
		for (int i = 0; i < this->m_size; i++)
		{
			this->paddress[i] = arr.paddress[i];
		}
		return *this;

	}
	//尾插法
	void push_back(const T & val)
	{
		//判断容量是否等于大小   容量已经塞满了
		if (this->m_capacity == this->m_size)
		{
			return;
		}
		this->paddress[this->m_size] = val;   //往数组中最后一位置插入
		this->m_size++; //更新数组大小
	}

	//尾删法
	void pop_back()
	{
		//让用户访问不到最后一个元素,即为尾删,逻辑删除
		if (this->m_size == 0)
		{
			return;
		}
		this->m_size--;
	}

	//通过下标方式访问数组中的元素  arr[0]  =  100
	T& operator[](int index)
	{
		return this->paddress[index];
	}

	//返回数组容量
	int getcapacity()
	{
		return this->m_capacity;
	}
	//返回数组大小
	int getsize()
	{
		return this->m_size;
	}

private:
	T * paddress;  //指针指向堆区开辟的真实数组

	int m_capacity;//数组容量
	int m_size; //数组大小
};
.cpp文件中的内容
#include
using namespace std;
#include "182-184 类模板封装案例.hpp"
//实现一个通用的数组类,要求如下:
//可以对内置数据类型和自定义数据类型的数据进行存储
//将数组中的数据存储到堆区
//构造函数中可以传入数组的容量
//提供对应的拷贝构造函数以及operator=防止浅拷贝问题
//提供尾插法和尾删法对数组的数据进行增加和删除
//可以通过下标的方式访问数组中的元素
//可以获取数组中当前元素的个数和数组的容量

//打印函数
void printinarray(myarray & arr)
{
	for (int i = 0; i < arr.getcapacity(); i++)
	{
		cout << arr[i] <arr1(5);  //有参构造函数构造数组,实例化对象arr1
	for (int i = 0; i < 5; i++)
	{
		//利用尾插法向数组中插入数据
		arr1.push_back(i);
	}
	cout << "arr1的打印输出为" << endl;

	printinarray(arr1);

	cout << "arr1的容量为" < arr2(arr1);   //拷贝构造的测试
	myarray arr2(5);
	arr2 = arr1;
	cout << "arr2的打印输出为" << endl;
	printinarray(arr2);

	//尾删
    arr2.pop_back();
	cout << "arr2尾删后" << endl;
	cout << "arr2的容量为" << arr2.getcapacity() << endl;
	cout << "arr2的大小为" << arr2.getsize() << endl;

	//myarrayarr3(100);
	//arr3 = arr1;
}


//测试自定义数据类型
class person
{
public:
	person() {};
	person(string name, int age)
	{
		this->m_name = name;
		this->m_age = age;
	}

	string m_name;
	int m_age;
};

void printpersonarray(myarray& arr)
{
	for (int i = 0; i < arr.getsize(); i++)
	{
		cout << "name: " << arr[i].m_name << "age= " << arr[i].m_age << endl;
	}
}
void test02()
{
	myarray arr(4);

	person p1("孙悟空", 999);
	person p2("韩信", 222);
	person p3("打击", 22);
	person p4("安其拉", 111222);

	//将数据插入到数组中
	arr.push_back(p1);
	arr.push_back(p2);
	arr.push_back(p3);
	arr.push_back(p4);

	//打印数组操作
	printpersonarray(arr);

	//输出容量
	cout << "arr的容量为" << arr.getcapacity() << endl;
	//输出大小
	cout << "arr的大小为" << arr.getcapacity() << endl;
}
int main() {

	test01();

	//test02();

	system("pause");
	return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/511523.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号