C++学习记录--提高Ⅰ(模板)

函数模板

基本概念

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

  • C++另一种编程思想称为 泛型编程 ,主要利用的技术就是模板
  • C++提供两种模板机制:函数模板和类模板
  • 模板不可以直接使用,它只是一个框架
  • 模板的通用并不是万能的

函数模板作用:
建立一个通用函数,其函数返回值类型和形参类型可以不具体制定,用一个虚拟的类型来代表。
语法:

template<typename T>  
函数声明或定义

解释:
template — 声明创建模板
typename — 表面其后面的符号是一种数据类型,可以用class代替
T — 通用的数据类型,名称可以替换,通常为大写字母

#include <iostream>
#include <string>
using namespace std;

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

void test01()
{
    
    
	int a = 10;
	int b = 20;
	swapInt(a, b);
	cout << a << b << endl;
}

//函数模板
template<typename T>
void mySwap(T &a, T &b)
{
    
    
	T temp = a;
	a = b;
	b = temp;
}

void test02()
{
    
    
	int a = 10;
	int b = 20;
	//利用模板交换
	//两种方式使用函数模板
	//1.自动类型推导
	// mySwap(a, b);
	//2. 显示指定类型
	mySwap<int>(a, b);
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
}

int main()
{
    
    
	test02();
	system("pause");
	return 0;
}

总结:
函数模板利用关键字 template
使用函数模板有两种方式:自动类型推导、显示指定类型
模板的目的是为了提高复用性,将类型参数化

注意事项:

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

案例

#include <iostream>
#include <string>
using namespace std;

//实现通用对数组进行排序的函数
// 规则 从大到小
// 算法 选择排序
// 测试 char数组 int数组

//交换数据模板
template<class T>
void mySwap(T &a, T &b)
{
    
    
	T temp = a;
	a = b;
	b = temp;
}

//排序算法模板
template<class T>
void mySort(T &arr, int len)
{
    
    
	for (int i = 0; i < len; i++)
	{
    
    
		int max = i;//认定最大值的下标
		for (int j = i + 1; j < len; j++)
		{
    
    
			if (arr[max] < arr[j])
			{
    
    
				max = j;//更新最大值下标
			}
		}
		if (max != i)
		{
    
    
			//交换max和i元素
			mySwap(arr[max], arr[i]);
		}
	}
}
//打印数组的模板
template<class T>
void printArr(T *arr, int len)
{
    
    
	cout << "数组从大到小排列为:" << endl;
	for (int i = 0; i < len; i++)
	{
    
    
		cout << arr[i] << " ";
	}
	cout << endl;
}

void test01()
{
    
    
	//测试 charArr
	char charArr[] = "absghc";
	int num = sizeof(charArr)/sizeof(char);
	mySort(charArr, num);
	printArr(charArr, num);
}

void test02()
{
    
    
	int intArr[] = {
    
     1,7,9,10,45,42,15,13,56,12,1 };
	int num = sizeof(intArr)/sizeof(int);
	mySort(intArr, num);
	printArr(intArr, num);
}

int main()
{
    
    
	test01();
	test02();
	system("pause");
	return 0;
}

普通函数与函数模板的区别

普通函数与函数模板区别:

  • 普通函数调用时可以发生自动类型转换(隐式类型转换)
  • 函数模板调用时,如果利用自动类型推导,不会发生隐式类型转换
  • 如果利用显示指定类型的方式,可以发生隐式类型转换
  • 建议使用显示指定类型的方式,调用函数模板,因为可以自己确定通用类型T

普通函数与函数模板的调用规则

调用规则如下:

  • 如果函数模板和普通函数都可以实现,优先调用普通函数
  • 可以通过空模板参数列表来强制调用函数模板
  • 函数模板也可以发生重载
  • 如果函数模板可以产生更好的匹配,优先调用函数模板
//普通函数与函数模板调用规则
void myPrint(int a, int b)
{
    
    
	cout << "调用的普通函数" << endl;
}

template<typename T>
void myPrint(T a, T b) 
{
    
     
	cout << "调用的模板" << endl;
}

template<typename T>
void myPrint(T a, T b, T c) 
{
    
     
	cout << "调用重载的模板" << endl; 
}

void test01()
{
    
    
	//1、如果函数模板和普通函数都可以实现,优先调用普通函数
	// 注意 如果告诉编译器  普通函数是有的,但只是声明没有实现,或者不在当前文件内实现,就会报错找不到
	int a = 10;
	int b = 20;
	myPrint(a, b); //调用普通函数

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

	//3、函数模板也可以发生重载
	int c = 30;
	myPrint(a, b, c); //调用重载的函数模板
	
	//4、 如果函数模板可以产生更好的匹配,优先调用函数模板
	char c1 = 'a';
	char c2 = 'b';
	myPrint(c1, c2); //调用函数模板
}

int main() {
    
    
	test01();
	system("pause");
	return 0;
}

总结:既然提供了函数模板,最好就不要提供普通函数,否则容易出现二义性

具体化模板

模板的重载,可以为特定的类型提供具体化的模板

#include<iostream>
using namespace std;
#include <string>

class Person
{
    
    
public:
	Person(string name, int age)
	{
    
    
		this->m_Name = name;
		this->m_Age = age;
	}
	string m_Name;
	int m_Age;
};

//普通函数模板
template<class T>
bool myCompare(T& a, T& b)
{
    
    
	if (a == b)
	{
    
    
		return true;
	}
	else
	{
    
    
		return false;
	}
}
//具体化,显示具体化的原型以template<>开头,并通过名称来指出类型,具体化优先于常规模板
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);
	//自定义数据类型,不会调用普通的函数模板
	//可以创建具体化的Person数据类型的模板,用于特殊处理这个类型
	bool ret = myCompare(p1, p2);
	if (ret)
	{
    
    
		cout << "p1 == p2 " << endl;
	}
	else
	{
    
    
		cout << "p1 != p2 " << endl;
	}
}

int main() {
    
    
	test01();
	test02();
	system("pause");
	return 0;
}

总结:

  • 利用具体化的模板,可以解决自定义类型的通用化
  • 学习模板并不是为了写模板,而是在STL能够运用系统提供的模板

类模板

基本概念

类模板作用:
建立一个通用类,类中的成员 数据类型可以不具体制定,用一个虚拟的类型来代表。
类模板和函数模板语法相似,在声明模板template后面加类,此类称为类模板

#include <string>
//类模板
template<class NameType, class AgeType> 
class Person
{
    
    
public:
	Person(NameType name, AgeType age)
	{
    
    
		this->mName = name;
		this->mAge = age;
	}
	void showPerson()
	{
    
    
		cout << "name: " << this->mName << " age: " << this->mAge << endl;
	}
public:
	NameType mName;
	AgeType mAge;
};

void test01()
{
    
    
	// 指定NameType 为string类型,AgeType 为 int类型
	Person<string, int>P1("孙悟空", 999);
	P1.showPerson();
}

int main() {
    
    
	test01();
	system("pause");
	return 0;
}

类模板与函数模板区别

主要有两点:

  • 类模板没有自动类型推导的使用方式
  • 类模板在模板参数列表中可以有默认参数
#include <string>
//类模板
template<class NameType, class AgeType = int> 
class Person
{
    
    
public:
	Person(NameType name, AgeType age)
	{
    
    
		this->mName = name;
		this->mAge = age;
	}
	void showPerson()
	{
    
    
		cout << "name: " << this->mName << " age: " << this->mAge << endl;
	}
public:
	NameType mName;
	AgeType mAge;
};
//1、类模板没有自动类型推导的使用方式
void test01()
{
    
    
	// Person p("孙悟空", 1000); // 错误 类模板使用时候,不可以用自动类型推导
	Person <string ,int>p("孙悟空", 1000); //必须使用显示指定类型的方式,使用类模板
	p.showPerson();
}
//2、类模板在模板参数列表中可以有默认参数
void test02()
{
    
    
	Person <string> p("猪八戒", 999); //类模板中的模板参数列表 可以指定默认参数
	p.showPerson();
}

int main() {
    
    
	test01();
	test02();
	system("pause");
	return 0;
}

成员函数创建时机

类模板中成员函数和普通类中成员函数创建时机是有区别的:

  • 普通类中的成员函数一开始就可以创建
  • 类模板中的成员函数在调用时才创建

类模板对象作函数参数

类模板实例化出的对象,向函数传参的方式
一共有三种传入方式:

  • 指定传入的类型 — 直接显示对象的数据类型(常用
  • 参数模板化 — 将对象中的参数变为模板进行传递
  • 整个类模板化 — 将这个对象类型 模板化进行传递
#include <string>
//类模板
template<class NameType, class AgeType = int> 
class Person
{
    
    
public:
	Person(NameType name, AgeType age)
	{
    
    
		this->mName = name;
		this->mAge = age;
	}
	void showPerson()
	{
    
    
		cout << "name: " << this->mName << " age: " << this->mAge << endl;
	}
public:
	NameType mName;
	AgeType mAge;
};
//1、指定传入的类型
void printPerson1(Person<string, int> &p) 
{
    
    
	p.showPerson();
}
void test01()
{
    
    
	Person <string, int >p("孙悟空", 100);
	printPerson1(p);
}
//2、参数模板化
template <class T1, class T2>
void printPerson2(Person<T1, T2>&p)
{
    
    
	p.showPerson();
	cout << "T1的类型为: " << typeid(T1).name() << endl;
	cout << "T2的类型为: " << typeid(T2).name() << endl;
}
void test02()
{
    
    
	Person <string, int >p("猪八戒", 90);
	printPerson2(p);
}

//3、整个类模板化
template<class T>
void printPerson3(T & p)
{
    
    
	cout << "T的类型为: " << typeid(T).name() << endl;
	p.showPerson();
}
void test03()
{
    
    
	Person <string, int >p("唐僧", 30);
	printPerson3(p);
}
int main() {
    
    
	test01();
	test02();
	test03();
	system("pause");
	return 0;
}

类模板与继承

当类模板碰到继承时,需要注意一下几点:

  • 当子类继承的父类是一个类模板时,子类在声明的时候,要指定出父类中T的类型
  • 如果不指定,编译器无法给子类分配内存
  • 如果想灵活指定出父类中T的类型,子类也需变为类模板
template<class T>
class Base
{
    
    
	T m;
};
//class Son:public Base  //错误,c++编译需要给子类分配内存,必须知道父类中T的类型才可以向下继承
class Son :public Base<int> //必须指定一个类型
{
    
    
};
void test01()
{
    
    
	Son c;
}
//类模板继承类模板 ,可以用T2指定父类中的T类型
template<class T1, class T2>
class Son2 :public Base<T2>
{
    
    
public:
	Son2()
	{
    
    
		cout << typeid(T1).name() << endl;
		cout << typeid(T2).name() << endl;
	}
	T1 obj;
};

void test02()
{
    
    
	Son2<int, char> child1;
}

类模板成员函数的类外实现

类模板中成员函数类外实现时,需要加上模板参数列表。

#include <string>

template<class T1, class T2>
class Person {
    
    
public:
	//成员函数类内声明
	Person(T1 name, T2 age);
	void showPerson();
public:
	T1 m_Name;
	T2 m_Age;
};
//构造函数 类外实现
template<class T1, class T2>
Person<T1, T2>::Person(T1 name, T2 age) {
    
    
	this->m_Name = name;
	this->m_Age = age;
}
//成员函数 类外实现
template<class T1, class T2>
void Person<T1, T2>::showPerson() {
    
    
	cout << "姓名: " << this->m_Name << " 年龄:" << this->m_Age << endl;
}
void test01()
{
    
    
	Person<string, int> p("Tom", 20);
	p.showPerson();
}

类模板分文件编写

问题:
类模板中成员函数创建时机是在调用阶段,导致分文件编写时链接不到
解决:

  • 解决方式1:直接包含.cpp源文件
  • 解决方式2:将声明和实现写到同一个文件中,并更改后缀名为.hpp,hpp是约定的名称,并不是强制

主要用方法2:.hpp

#pragma once
#include <iostream>
using namespace std;
#include <string>

template<class T1, class T2>
class Person {
    
    
public:
	Person(T1 name, T2 age);
	void showPerson();
public:
	T1 m_Name;
	T2 m_Age;
};

//构造函数 类外实现
template<class T1, class T2>
Person<T1, T2>::Person(T1 name, T2 age) {
    
    
	this->m_Name = name;
	this->m_Age = age;
}

//成员函数 类外实现
template<class T1, class T2>
void Person<T1, T2>::showPerson() {
    
    
	cout << "姓名: " << this->m_Name << " 年龄:" << this->m_Age << endl;
}

类模板与友元

学习目标:

  • 掌握类模板配合友元函数的类内和类外实现

全局函数类内实现 - 直接在类内声明友元即可
全局函数类外实现 - 需要提前让编译器知道全局函数的存在

#include <string>

//2、全局函数配合友元  类外实现 - 先做函数模板声明,下方在做函数模板定义,在做友元
template<class T1, class T2> class Person;
//如果声明了函数模板,可以将实现写到后面,否则需要将实现体写到类的前面让编译器提前看到
//template<class T1, class T2> void printPerson2(Person<T1, T2> & p); 

template<class T1, class T2>
void printPerson2(Person<T1, T2> & p)
{
    
    
	cout << "类外实现 ---- 姓名: " << p.m_Name << " 年龄:" << p.m_Age << endl;
}

template<class T1, class T2>
class Person
{
    
    
	//1、全局函数配合友元   类内实现
	friend void printPerson(Person<T1, T2> & p)
	{
    
    
		cout << "姓名: " << p.m_Name << " 年龄:" << p.m_Age << endl;
	}
	//全局函数配合友元  类外实现
	friend void printPerson2<>(Person<T1, T2> & p);
public:
	Person(T1 name, T2 age)
	{
    
    
		this->m_Name = name;
		this->m_Age = age;
	}
private:
	T1 m_Name;
	T2 m_Age;

};
//1、全局函数在类内实现
void test01()
{
    
    
	Person <string, int >p("Tom", 20);
	printPerson(p);
}
//2、全局函数在类外实现
void test02()
{
    
    
	Person <string, int >p("Jerry", 30);
	printPerson2(p);
}
int main() {
    
    
	//test01();
	test02();
	system("pause");
	return 0;
}

总结:建议全局函数做类内实现,用法简单,而且编译器可以直接识别

类模板案例

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

  1. 可以对内置数据类型以及自定义数据类型进行储存;
  2. 将数组中的数据存储到堆区;
  3. 构造函数中可以传入数组的容量;
  4. 提供对应的拷贝构造函数以及operator = 防止浅拷贝问题;
  5. 提供尾插法和尾删法对数组中的数据进行增加和删除;
  6. 可以通过下标的方式访问数组中的元素;
  7. 可以获取数组中当前元素个数和数组的容量。
// MyArray.hpp
#pragma once
#include <iostream>
using namespace std;

template<class T>
class MyArray
{
    
    
public:
	MyArray() {
    
    };
	//有参构造 参数 容量
	MyArray(int capacity)
	{
    
    
		//cout << "有参构造" << endl;
		this->m_Capacity = capacity;
		this->m_Size = 0;
		this->pAddress = new T[this->m_Capacity];
	}
	MyArray(const MyArray& arr)
	{
    
    
		//cout << "拷贝构造" << endl;
		this->m_Capacity = arr.m_Capacity;
		this->m_Size = arr.m_Size;
		//深拷贝
		this->pAddress = new T[arr.m_Capacity];
		//将arr中的数据都拷贝过来
		for (int i = 0; i < this->m_Size; i++)
		{
    
    
			this->pAddress[i] = arr.pAddress[i];
		}
	}
	// operator= 防止浅拷贝问题
	MyArray& operator=(const MyArray &arr)
	{
    
    
		//cout << "operator = 调用" << endl;
		//先判断原来堆区是否有数据,如果有先释放
		if (this->pAddress != NULL)
		{
    
    
			delete[] this->pAddress;
			this->pAddress = NULL;
			this->m_Capacity = 0;
			this->m_Size = 0;
		}		
		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;
	}
	~MyArray()
	{
    
    
		if (this->pAddress != NULL)
		{
    
    
			//cout << "析构函数" << endl;
			delete[] this->pAddress;
			this->pAddress = NULL;
		}
	}
private:
	T * pAddress;
	int m_Size;
	int m_Capacity;

};
// main.cpp
#include <iostream>
#include <string>
using namespace std;
#include "MyArray.hpp"

void PrintIntArr(MyArray<int>& p)
{
    
    
	for (int i = 0; i < p.getSize(); i++)
	{
    
    
		cout << p[i] << " ";
	}
	cout << endl;
}

//测试内置数据类型
void test01()
{
    
    
	MyArray<int> p1(10);

	for (int i = 0; i < 5; i++)
	{
    
    
		p1.Push_Back(i + 1);
	}
	cout << "p1的打印输出为:" << endl;
	PrintIntArr(p1);

	cout << "容量为:" << p1.getCapacity() << endl;
	cout << "大小为:" << p1.getSize() << endl;

	MyArray<int> p2(p1);
	cout << "p2的打印输出为:" << endl;
	PrintIntArr(p2);

	//尾删
	p2.Pop_Back();
	cout << "p2尾删后:" << endl;
	PrintIntArr(p2);
	cout << "容量为:" << p2.getCapacity() << endl;
	cout << "大小为:" << p2.getSize() << endl;
}

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

	string m_Name;
	int m_Age;
};
void printPersonArr(MyArray<Person>& p)
{
    
    
	for (int i = 0; i < p.getSize(); i++)
	{
    
    
		cout << "姓名:" << p[i].m_Name << "\t年龄:" << p[i].m_Age << endl;
	}
}
void test02()
{
    
    
	MyArray<Person> arr(8);

	Person p1("王昭君",20);
	Person p2("貂蝉", 19);
	Person p3("赵云",25);
	Person p4("妲己", 17);
	//将数据尾插
	arr.Push_Back(p1);
	arr.Push_Back(p2);
	arr.Push_Back(p3);
	arr.Push_Back(p4);
	//打印数组
	cout << "自定义数据输出:" << endl;
	printPersonArr(arr);

	cout << "容量为:" << arr.getCapacity() << endl;
	cout << "大小为:" << arr.getSize() << endl;
}
int main()
{
    
    
	test01();
	test02();
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_34551090/article/details/113176744