ShuangChenYue ShuangChenYue
首页
  • Cpp之旅
  • Cpp专栏
  • Effective_CPP
  • muduo网络库
  • Unix环境高级编程
  • Cpp提高编程
  • 计算机网络
  • 操作系统
  • 数据结构
  • Linux
  • 算法
  • 基础篇
  • MySql
  • Redis
  • 电子嵌入式通信协议
  • 深入浅出SSD
  • 文件系统
  • 汇编语言
  • STM32
  • 随笔(持续更新)
  • Git知识总结
  • Git 创建删除远程分支
  • nvm使用小结
  • 虚拟机固定 IP 地址
  • Shell 脚本学习笔记
  • VScode 插件 CodeGeeX 使用教程
  • KylinV10 将项目上传至 Github教程
  • KylinV10 安装 MySQL 教程(可防踩雷)
  • kylinV10-SP1 安装 QT
  • 高并发内存池
  • USBGUARD 项目编译环境配置
  • Power_Destory 项目
  • U 盘清除工具编译教程
  • 个人博客代码推送教程
  • HTML与CSS
  • JS学习
  • Vue3入门
  • Vue3进阶
  • 黑马Vue3
  • MFC编程随记
  • MFC实现ini配置文件的读取
  • MFC实现点击列表头排序
  • 贴图法美化Button按钮
  • 如何高效阅读嵌入式项目代码
  • NAND Flash
  • ARM 处理器
  • 嵌入式基础知识-存储器
  • 闪存存储和制造技术概述
  • 芯片IO驱动力
  • 主流先进封装技术介绍
  • 虎牙C++技术面经
  • 金山一面复习
  • 完美世界秋招 C++ 游戏开发面经(Cpp部分)
  • 博客搭建
  • 网站收藏箱
首页
  • Cpp之旅
  • Cpp专栏
  • Effective_CPP
  • muduo网络库
  • Unix环境高级编程
  • Cpp提高编程
  • 计算机网络
  • 操作系统
  • 数据结构
  • Linux
  • 算法
  • 基础篇
  • MySql
  • Redis
  • 电子嵌入式通信协议
  • 深入浅出SSD
  • 文件系统
  • 汇编语言
  • STM32
  • 随笔(持续更新)
  • Git知识总结
  • Git 创建删除远程分支
  • nvm使用小结
  • 虚拟机固定 IP 地址
  • Shell 脚本学习笔记
  • VScode 插件 CodeGeeX 使用教程
  • KylinV10 将项目上传至 Github教程
  • KylinV10 安装 MySQL 教程(可防踩雷)
  • kylinV10-SP1 安装 QT
  • 高并发内存池
  • USBGUARD 项目编译环境配置
  • Power_Destory 项目
  • U 盘清除工具编译教程
  • 个人博客代码推送教程
  • HTML与CSS
  • JS学习
  • Vue3入门
  • Vue3进阶
  • 黑马Vue3
  • MFC编程随记
  • MFC实现ini配置文件的读取
  • MFC实现点击列表头排序
  • 贴图法美化Button按钮
  • 如何高效阅读嵌入式项目代码
  • NAND Flash
  • ARM 处理器
  • 嵌入式基础知识-存储器
  • 闪存存储和制造技术概述
  • 芯片IO驱动力
  • 主流先进封装技术介绍
  • 虎牙C++技术面经
  • 金山一面复习
  • 完美世界秋招 C++ 游戏开发面经(Cpp部分)
  • 博客搭建
  • 网站收藏箱
  • Cpp之旅

  • Cpp专栏

  • Effetcive_CPP

  • muduo网络库

  • Unix环境高级编程

  • Cpp提高编程

    • 函数模板
    • 类模板
      • 2、类模板
        • 2.1 类模板语法
        • 2.2 类模板和函数模板的区别
        • 2.3 类模板中成员函数创建时机
        • 2.4 类模板对象做函数参数
        • 2.5 类模板与继承
        • 2.6 类模板成员函数类外实现
        • 2.7 类模板和友元
        • 2.8 类模板案例
    • 初识STL
    • string 容器
    • vector 容器
    • deque 容器
    • stack 容器
    • queue 容器
    • list 容器
    • set 容器
    • map 容器
    • STL 函数对象
  • CPP语言
  • Cpp提高编程
霜晨月
2023-12-15
目录

类模板

# 2、类模板

# 2.1 类模板语法

建立一个通用类,类中的成员、数据类型可以不具体制定,用一个虚拟的类型来代表。

template<typename T>
// 类
1
2
  • template:声明创建模板
  • typename:表名其后面的符号是一种数据类型,可以用 class 代替
  • T:通用的数据类型,名称可以替换,通常为大写字母
#include <iostream>
using namespace std;
// 类模板
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;
    AgeTyep mAge;
};

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

int main() {
    test01();
    system("pause");
    return 0;
}
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

总结:

  • 类模板和函数模板语法类似,在声明模板 template 后面加类,此类称为类模板

# 2.2 类模板和函数模板的区别

  • 类模板没有自动类型推导的使用方式
  • 类模板在模板参数列表中可以有默认参数
#include <iostream>
using namespace std;
// 类模板
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、类模板没有自动类型推导的使用方式
//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;
}
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
32
33
34
35
36
37
38
39

总结:

  • 类模板使用只能用显示指定类型方式
  • 类模板中的模板参数列表可以有默认参数

# 2.3 类模板中成员函数创建时机

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

  • 普通类中的成员函数一开始就可以创建
  • 类模板中的成员函数在调用时才创建
#include <iostream>
using namespace std;
class Person1 {
    public:
    void showPerson1() {
        cout << "Person1 show" << endl;
    }
};
class Person2 {
    public:
    void showPerson2() {
        cout << "Person2 show" << endl;
    }
};

template<class T>
    class MyClass {
        public:
        T obj;
        // 类模板中的成员函数,并不是一开始就创建的,而是在模板调用时再生成
        void fun1() { obj.showPerson1(); }
        void fun2() { obj.showPerson2(); }
    };
void test01()
{
    MyClass<Person1> m;
    m.fun1();
    // m.fun2();		// 编译会出错,说明函数调用才会去创建成员函数
}
int main() {
    test01();
    system("pause");
    return 0;
}
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
32
33
34

总结:

  • 类模板中的成员函数并不是一开始就创建的,在调用时才去创建

# 2.4 类模板对象做函数参数

  • 类模板实例化出的对象,向函数传参的方式

共三种传入方式:

  1. 指定传入的类型:直接显示对象的数据类型
  2. 参数模板化:将对象中的参数变为模板进行传递
  3. 整个类模板化:将这个对象类型模板化进行传递
#include <iostream>
#include <string>
using namespace std;

// 类模板
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;
}
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

总结:

  • 通过类模板创建的对象,可以有三种方式向函数中进行传参
  • 使用比较广泛的是第一种:指定传入的类型

# 2.5 类模板与继承

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

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

# 2.6 类模板成员函数类外实现

#include <iostream>
using namespace std;

// 类模板中成员函数类外实现
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();
}
int main() {
	test01();
	system("pause");
	return 0;
}
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
32
33
34
35
36
37
38

总结:

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

# 2.7 类模板和友元

  • 全局函数类内实现:直接在类内声明友元即可
  • 全局函数类外实现:需要提前让编译器知道全局函数的存在
#include <iostream>
#include <string>
using namespace std;

// 2、全局函数配合友元 类外实现:先做函数模板声明,下方在做函数模板定义,在做友元
template<class T1, class T2>class Person;

// 如果声明了函数模板,可以将实现写到后面,否则需要将实现体写到类的前面让编译器提前看到
template<class T1, class T2> void printPerson2(Person<T1, T2>& p);

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

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

int main() {
	test01();
	test02();
	system("pause");
	return 0;
}
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

总结:

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

# 2.8 类模板案例

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

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

myArray.hpp文件

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

template<class T>
class MyArray {
public:
	// 构造函数
	MyArray(int capatity) {
		this->m_Capacity = capatity;
		this->m_Size = 0;
		pAddress = new T[this->m_Capacity];
	}
	// 拷贝函数
	MyArray(const MyArray& arr) {
		this->m_Capacity = arr.m_Capacity;
		this->m_Size = arr.m_Size;
		this->pAddress = new T[this->m_Capacity];
		for (int i = 0; i < this->m_Size; ++i) {
			// 如果T为对象,而且还包含指针,必须需要重载 = 操作符,因为这个等号不是构造 而是赋值,
			// 普通类型可以直接 = 但是指针类型需要深拷贝
			this->pAddress[i] = arr.pAddress[i];
		}
	}
	// 重载 = 操作符 防止浅拷贝问题
	MyArray& operator=(const MyArray& myarray) {
		if (this->pAddress != nullptr) {
			delete[] this->pAddress;
			this->m_Capacity = 0;
			this->m_Size = 0;
		}

		this->m_Capacity = myarray.m_Capacity;
		this->m_Size = myarray.m_Size;
		this->pAddress = new T[this->m_Capacity];
		for (int i = 0; i < this->m_Size; ++i) {
			this->pAddress[i] = myarray[i];
		}
		return *this;
	}
	// 重载 [] 操作符 arr[0]
	T& operator[](int index) {
		return this->pAddress[index];//不考虑越界,用户自己去处理
	}
	
	// 尾插法
	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--;
	}

	//获取数组容量
	int getCapacity() {
		return this->m_Capacity;
	}

	// 获取数组大小
	int getSize() {
		return this->m_Size;
	}

	~MyArray() {
		if (this->pAddress != nullptr) {
			delete[] this->pAddress;
			this->pAddress = nullptr;
			this->m_Capacity = 0;
			this->m_Size = 0;
		}
	}
private:
	T* pAddress;	// 指向一个堆空间,这个空间存储真正的数据
	int m_Capacity; // 容量
	int m_Size;		// 大小
};
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

myArray.cpp文件

#include "myArray.hpp"

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

// 测试内置数据类型
void test01() {
	MyArray<int> array1(10);
	for (int i = 0; i < 10; ++i) {
		array1.push_back(i);
	}
	cout << "array1打印输出:" << endl;
	printIntArray(array1);
	cout << "array1的大小:" << array1.getSize() << endl;
	cout << "array1的容量:" << array1.getCapacity() << endl;
	cout <<-----------------------------------" << endl;

	MyArray<int> array2(array1);
	array2.pop_back();
	cout << "array2打印输出:" << endl;
	printIntArray(array2);
	cout << "array2的大小:" << array2.getSize() << endl;
	cout << "array2的容量:" << array2.getCapacity() << endl;
}

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

public:
	string m_Name;
	int m_Age;
};
void printPersonArray(MyArray<Person>& personArr) {
	for (int i = 0; i < personArr.getSize(); ++i) {
		cout << "姓名:" << personArr[i].m_Name << " 年龄:" << personArr[i].m_Age << endl;
	}
}

void test02() {
	// 创建数组
	MyArray<Person>pArray(10);
	Person p1("孙悟空", 999);
	Person p2("韩信", 20);
	Person p3("妲己", 18);
	Person p4("王昭君", 15);
	Person p5("赵云", 24);
	// 插入数据
	pArray.push_back(p1);
	pArray.push_back(p2);
	pArray.push_back(p3);
	pArray.push_back(p4);
	pArray.push_back(p5);
	printPersonArray(pArray);

	cout << "pArray的大小:" << pArray.getSize() << endl;
	cout << "pArray的容量:" << pArray.getCapacity() << endl;
}

int main() {
	test01();
	test02();

	system("pause");
	return 0;
}
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
上次更新: 2024/6/3 14:54:44
函数模板
初识STL

← 函数模板 初识STL→

Theme by Vdoing | Copyright © 2023-2024 霜晨月
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式