C++提高编程——模板

这篇具有很好参考价值的文章主要介绍了C++提高编程——模板。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

C++提高编程

本阶段主要针对C++泛型编程STT技术做详细讲解,探讨C++更深层的使用

1模板

1.1模板的概念

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

例如生活中的模板

寸照片模板:

1.2函数模板

  1. C++另一种编程思想称为 泛型编程,主要利用的技术就是模板
  2. C++提供两种模板机制:函数模板和类模板

1.2.1函数模板语法

函数模板作用:

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

语法:

//函数声明或定义

template<typename T>

解释:

  1. template —— 声明创建模板
  2. typename —— 表面其后面的符号是一种数据类型,可以用class代替
  3. T —— 通用的数据类型,名称可以替换,通常为大写字母
#include<iostream>;
using namespace std;
//两个整型交换函数
void swapInt(int &a, int &b)
{
	int temp = a;
	a = b;
	b = temp;
}
//函数模板
template<typename T>//声明一个模板,告诉编译器后面代码中紧跟着的T不要报错,T是一个通用数据类型。
void mySwap(T& a, T& b)
{
	T temp = a;
	a = b;
	b = temp;
}
//交换两个浮点型函数
void swapDouble(double& a, double& b)
{
	double temp = a;
	a = b;
	b = temp;
}
//测试
void test01()
{
	int a = 10;
	int b = 20;
	/*swapInt(a,b);*/
	//利用函数模板交换
	//两种方式使用函数模板
	//1、自动类型推导
	//mySwap(a,b);
	//2、显示指定类型
	mySwap<int>(a, b);
	cout << "a=" << a << endl;
	cout << "b=" << b << endl;

	//double c = 1.1;
	//double d = 2.2;
	//swapDouble(c, d);
	//cout << "c=" << c << endl;
	//cout << "d=" << d << endl;
}
//函数模板
int main()
{
	test01();

	system("pause");//按任意键继续
	return 0;  
}

总结:

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

1.2.2函数模板注意事项

注意事项:

  1. 自动类型推导,必须推导出---致的数据类型T,才可以使用
  2. 模板必须要确定出T的数据类型,才可以使用
#include<iostream>;
using namespace std;
//函数模板注意事项
template<typename T>//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;
	char c = 'c';
	mySwap(a, b);//正确
	//mySwap(a, c);//错误!!!推导不出一致的T类型。
	cout << "a=" << a << endl;
	cout << "b=" << b << endl;
}
//2、模板必须要确定出T的数据类型,才可以使用。
template<typename T>//typename可以替换class
void func()
{
	cout << "func 调用" << endl;
}
void test02()
{
	func<int>();
}
//主函数
int main()
{
	test01();
	test02();

	system("pause");//按任意键继续
	return 0;
}

总结

使用模板时必须确定出通用数据类型T,并且能够推导出一致的类型

1.2.3函数模板案例

案例描述:

  1. 利用函数模板封装一个排序的函数,可以对不同数据类型数组进行排序
  2. 排序规则从大到小,排序算法为选择排序
  3. 分别利用char数组int数组进行测试
#include<iostream>;
using namespace std;
//实现通用 对数组进行排序的函数
//规则  从大到小
//算法 选择
//测试 char 数组、int数组

//交换函数模板
template<typename T>
void mySawp(T& a, T& b)
{
	T temp = a;
	a = b;
	b = temp;
}
//排序算法
template<typename T>
void mySort(T arr[],int len)
{
	for (int i = 0; i < len; i++)
	{
		//认定的最大值 比 遍历出的数值 要小,说明j下标的元素才是真正的最大值
		int max = i;//认定最大值的下标
		for (int j = i + 1; j < len; j++)
		{
			if (arr[max] < arr[j])
			{
				max = j;//更新最大值下标
			}
		}
		if (max != i)
		{
			//交换max和i元素
			mySawp(arr[max], arr[i]);
		}
	}
}
//打印数组的模板
template<typename T>
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 intArr[] = {7,5,1,3,9,2,4,6,8};
	int num = sizeof(intArr) / sizeof(int);
	mySort(intArr, num);
	printArray(intArr, num);
}

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

	system("pause");//按任意键继续
	return 0;
}

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

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

  1. 普通函数调用时可以发生自动类型转换 (隐式类型转换)
  2. 函数模板调用时,如果利用自动类型推导,不会发生隐式类型转换
  3. 如果利用显示指定类型的方式,可以发生隐式类型转换
#include<iostream>;
using namespace std;
//普通函数与函数模板区别:
//1、普通函数调用可以发生隐式类型转换
//2、函数模板 用自动类型推导,不可以发生隐式类型转换
//3、函数模板 用显示指定类型,可以发生隐式类型转换

//普通函数
int myAdd01(int a, int b)
{
	return a + b;
}
//函数模板
template<typename T>
T myAdd02(T a, T b)
{
	return a + b;
}

void test01()
{
	int a = 10;
	int b = 20;
	char c = 'c';//a——97  c——99;
	cout << myAdd01(a, b) << endl;
	cout << myAdd01(a, c) << endl;

	//自动类型推导 不会发生隐式类型转换
	cout << myAdd02(a, b) << endl;
	//cout << myAdd02(a, c) << endl;//错误!!!

	//显示指定类型 会发生隐式类型转换
	cout << myAdd02<int>(a, c) << endl;
}

int main()
{
	test01();

	system("pause");//按任意键继续
	return 0;
}

总结: 建议使用显示指定类型的方式,调用函数模板,因为可以自己确定通用类型T。

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

调用规则如下:

1.如果函数模板和普通函数都可以实现,优先调普通函数

2.可通过空模板参数列表强制调用函数模板

3.函数模板也可以发生重载

4.如果函数模板可以产生更好的匹配,优先调用函数模板

#include<iostream>;
using namespace std;

//普通函数与函数模板调用规则
//1、如果函数模板和普通函数都可以调用,优先调用普通函数
//2、可以通过空模板参数列表 强制调用 函数模板
//3、函数模板可以发生函数重载
//4、如果函数模板可以产生更好的匹配,优先调用函数模板
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()
{
	int a = 10;
	int b = 20;
	//myPrint(a, b);

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

	myPrint(a, b,100);//函数重载

	//如果函数模板产生更好的匹配,优先调用函数模板
	char c1 = 'a';
	char c2 = 'b';
	myPrint(c1,c2);//调用函数模板
}

int main()
{
	test01();

	system("pause");//按任意键继续
	return 0;
}

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

1.2.6 模板的局限性

局限性:

模板的通用性并不是万能的

#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<typename T>
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 << "p1==p2" << endl;
	}
	else
	{
		cout << "p1!=p2" << endl;
	}
}

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

	system("pause");//按任意键继续
	return 0;
}

总结:

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

1.3类模板

1.3.1类模板语法

类模板作用

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

template<typename T>

解释:

Template——声明创建模板

Typename——表面其后面的符号是一种数据类型,可以用class代替

T——通用的数据类型,名称可以替换,通常为大写字母

#include<iostream>;
using namespace std;
#include<string>;
//类模板
template<class NameType,class AgeType>
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;
};
//测试
void test01()
{
	Person<string,int> p1("孙悟空",999);
	p1.showPerson();
}

int main()
{
	test01();

	system("pause");//按任意键继续
	return 0;
}

总结:类模板和函数模板语法相似,在声明模板template后面加类,此类称为类模板。

1.3.2 类模板与函数模板区别

类模板与函数模板区别主要有两点:

1.类模板没有自动类型推导的使用方式

2.类模板在模板参数列表中可以有默认参数

#include<iostream>;
using namespace std;
#include<string>;
//类模板与函数模板区别主要有两点:
template<class NameType,class AgeType = int>//仅类模板可以使用int
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);//错误,无法用自动类型推导
	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. 类模板中的模板参数列表可以有默认参数。

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

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

  1. 普通类中的成员函数一开始就可以创建
  2. 类模板中的成员函数在调用时才创建
#include<iostream>;
using namespace std;
#include<string>;
//普通类中的成员函数一开始就可以创建
//类模板中的成员函数在调用时才创建
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 func1()
	{
		obj.showPerson1();
	}
	void func2()
	{
		obj.showPerson2();
	}
};
//测试
void test01()
{
	MyClass<Person1>m;
	m.func1();
	//MyClass<Person2>m;
	//m.func2();
}

int main()
{
	test01();

	system("pause");//按任意键继续
	return 0;
}

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

1.3.4 类模板对象做函数参数

学习目标:

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

一共有三种传入方式

1.指定传入的类型  ——直接显示对象的数据类型

2.数模板化       ——将对象中的参数变为模板进行传递

3.整个类模板化   ——将这个对象类型 模板化进行传递

#include<iostream>;
using namespace std;
#include<string>;
//类模板对象做函数参数
template<class T1,class T2>
class Person
{
public:
	Person(T1 name,T2 age)
	{
		this->m_Name = name;
		this->m_Age = age;
	}
	void showPerson()
	{
		cout << "姓名:" << this->m_Name << " 年龄:" << this->m_Age << endl;
	}
	T1 m_Name;
	T2 m_Age;
};
//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 )//引用
{
	p.showPerson();
	cout << "T的类型为:" << typeid(T).name() << endl;//查看数据中的类型命令。
}
void test03()
{
	Person<string, int>p("唐僧", 30);
	printPerson3(p);
}

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

	system("pause");//按任意键继续
	return 0;
}

总结:

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

1.3.5 类模板与继承

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

  1. 当子类继承的父类是一个类模板时,子类在声明的时候,要指定出父类中T的类型
  2. 如果不指定,编译器无法给子类分配内存
  3. 如果想灵活指定出父类中T的类型,子类也需变为类模板
#include<iostream>;
using namespace std;
#include<string>;
//类模板与继承
template<class T>
class Base
{
public:
	T m;
};
//class Son:public Base//错误,必须要知道父类中的T类型,才能继承给子类。
//1、当子类继承的父类是一个类模板时,子类在声明的时候,要指定出父类中T的类型
class Son1:public Base<int>//继承
{
public:

};
//测试
void test01()
{
	Son1 s1;
}
//2、如果想灵活指定出父类中T的类型,子类也需变为类模板
template<class T1,class T2>
class Son2 :public Base<T2>//继承
{
public:
	Son2()
	{
		cout << "T1的类型为:" << typeid(T1).name() << endl;
		cout << "T2的类型为:" << typeid(T2).name() << endl;
	}
	T1 obj;
};
void test02()
{
	Son2<int,char>s2;
}

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

	system("pause");//按任意键继续
	return 0;
}

总结:如果父类是类模板,子类需要指定出父类中T的数据类型。

#include<iostream>;
using namespace std;
#include<string>;
//类模板成员函数类外实现
template<class T1,class T2>
class Person
{
public:
	Person(T1 name, T2 age);
		/*{
			this->m_Name = name;
			this->m_Age = age;
		}*/
	void showPerson();
	/*{
		cout << "姓名:" << this->m_Name << " 年龄:" << this->m_Age << endl;
	}*/
	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.3.7 类模板分文件编写

学习目标:

  1. 掌握类模板成员函数分文件编写产生的问题以及解决方式

问题:

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

解决:

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

示例:

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

类模板分文件编写.cpp中代码:

#include<iostream>
using namespace std;

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

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

类模板分文件编写问题以及解决
//template<class T1,class T2>
//class Person
//{
//public:
//	Person(T1 name, T2 age);
//	void showPerson();
//	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("Jerry", 18);
	p.showPerson();
}

int main()
{
	test01();

	system("pause");//按任意键继续
	return 0;
}

总结:主流的解决方式是第二种,将类模板成员函数写到一起,并将后缀名改为.hpp

1.3.8 类模板与友元

学习目标:

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

全局函数类内实现——直接在类内声明友元即可

全局函数类外实现——需要提前让编译器知道全局函数的存在

#include<iostream>;
using namespace std;
#include<string>;
//类模板与友元
//通过全局函数 打印Person信息
//提前让编译器知道Person类存在
template<class T1, class T2>
class Person;
//类外实现
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
{
	//全局函数 类内实现
	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", 20);
	printPerson2(p);
}

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

	system("pause");//按任意键继续
	return 0;
}

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

1.3.9 类模板案例

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

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

思路分析:

C++提高编程——模板,C / C++,c++

 MyArrey.hpp中的代码:

//自己的通用的数组类
#pragma once
#include<iostream>
using namespace std;

template<class T>
class MyArrey
{
public:
	//有参构造 参数 容量
	MyArrey(int capacity)
	{
		cout << "MyArrey有参构造调用" << endl;
		this->m_Capacity = capacity;
		this->m_Size = 0;
		this->pAddress = new T[this->m_Capacity];
	}
	//拷贝构造
	MyArrey(const MyArrey& arr)
	{
		cout << "MyArrey拷贝构造调用" << 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
	MyArrey& operator=(const MyArrey& arr)
	{
		cout << "MyArrey 的 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];
		//将arr中的数据都拷贝过来
		for (int i = 0; i < this->m_Size; i++)
		{
			this->pAddress[i] = arr.pAddress[i];
		}
		return *this;
	}
	//析构函数
	~MyArrey()
	{
		if (this->pAddress!=NULL)
		{
			cout << "MyArrey析构函数调用" << endl;
			delete[] this->pAddress;
			this->pAddress = NULL;
		}
	}

private:
	T* pAddress;//指针指向堆区开辟的真实数组
	int m_Capacity;//数组的容量
	int m_Size;//数组大小
};

类模板案例-数组类封装.cpp中的代码:

#include<iostream>;
using namespace std;
#include<string>;
#include"MyArray.hpp"

void test01()
{
	MyArrey<int>arr1(5);
	MyArrey<int>arr2(arr1);
	MyArrey<int>arr3(100);
	arr3 = arr1;
}

int main()
{
	test01();

	system("pause");//按任意键继续
	return 0;
}

尾插法/尾删法——案例完整代码:

MyArrey.hpp中的代码:

//自己的通用的数组类
#pragma once
#include<iostream>
using namespace std;

template<class T>
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(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;
		}
		//深拷贝
		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];
		}
		return *this;
	}
	//尾插法20230817
	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。//重载operator
	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 << "MyArray析构函数调用" << endl;
			delete[] this->pAddress;
			this->pAddress = NULL;
		}
	}
private:
	T* pAddress;//指针指向堆区开辟的真实数组
	int m_Capacity;//数组的容量
	int m_Size;//数组大小
};

类模板案例-数组类封装.cpp中的代码:

#include<iostream>;
using namespace std;
#include<string>;
#include"MyArray.hpp"

void printIntArray(MyArray<int>&arr)
{
	for (int i = 0; i < arr.getSize(); i++)
	{
		cout << arr[i] << endl;
	}
}
void test01()
{
	MyArray<int>arr1(5);
	for (int i = 0; i < 5; i++)
	{
		//利用尾插法向数组中插入数据
		arr1.Push_Back(i);
	}
	cout << "arr1的打印输出为:" << endl;
	printIntArray(arr1);
	cout << "arr1的容量为:" << arr1.getCapacity() << endl;
	cout << "arr1的大小为:" << arr1.getSize() << endl;

	MyArray<int>arr2(arr1);
	cout << "arr2的打印输出为:" << endl;
	printIntArray(arr2);
	//尾删
	arr2.Pop_Back();
	cout << "arr2尾删后:" << endl;
	cout << "arr2的容量为:" << arr2.getCapacity() << endl;
	cout << "arr2的大小为:" << arr2.getSize() << endl;
	
	/*MyArray<int>arr3(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<Person> &arr)
{
	for (int i = 0; i < arr.getSize(); i++)
	{
		cout << "姓名:" << arr[i].m_Name << "年龄" << arr[i].m_Age << endl;
	}
}
void test02()
{
	MyArray<Person> arr(10);
	Person p1("孙悟空",999);
	Person p2("韩信", 30);
	Person p3("妲己", 20);
	Person p4("赵云", 25);
	Person p5("安其拉", 27);
	//将数据插入到数组中
	arr.Push_Back(p1);
	arr.Push_Back(p2);
	arr.Push_Back(p3);
	arr.Push_Back(p4);
	arr.Push_Back(p5);
	//打印数组
	printPersonArray(arr);
	//输出容量
	cout << "arr的容量为:" << arr.getCapacity() << endl;
	//输出大小
	cout << "arr的大小为:" << arr.getSize() << endl;
}

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

	system("pause");//按任意键继续
	return 0;
}

总结:

能够利用所学知识点实现通用的数组

模板结束。文章来源地址https://www.toymoban.com/news/detail-662501.html

到了这里,关于C++提高编程——模板的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • C++提高编程

            ●本阶段主要针对C++泛型编程和STL技术做详细讲解,探讨C++更深层的使用 1模板 1.1模板的概念 模板就是建立通用的模具,大大提高复用性 例如生活中的模板 一寸照片模板:  1.2函数模板         ●C++另一种编程思想称为泛型编程,主要利用的技术就是模板  

    2024年02月03日
    浏览(22)
  • 第一百一十四天学习记录:C++提高:类模板案例(黑马教学视频)

    main.cpp代码: myarray.hpp代码: 输出: 总结:能够利用所学知识点实现通用的数组。 个人感悟:学习了这个案例之后接下来的课程就是STL了,STL其实在我工作中写代码时经常碰到,尤其是在读同事代码的时候,因为没有学过,通过自行百度获得碎片的知识导致读起来很很吃力

    2024年02月16日
    浏览(37)
  • 【C++】——模板(泛型编程+函数模板+类模板)

    之前我们学习了函数重载,让我们在写相似函数的时候非常方便,但函数重载还有很多不足的地方,比如,每次写相似函数的时候,都要我们重新重载一个逻辑、代码几乎一样的函数,这就导致了我们的效率变低,所以我们今天来学习C++模板的相关知识点,学习完模板之后,

    2024年02月05日
    浏览(36)
  • C++核心编程——内存分区、引用、函数提高和函数重载

    本专栏记录C++学习过程包括C++基础以及数据结构和算法,其中第一部分计划时间一个月,主要跟着黑马视频教程,学习路线如下, 不定时更新,欢迎关注 。 当前章节处于: ---------第1阶段-C++基础入门 ---------第2阶段实战-通讯录管理系统, ==== 第3阶段-C++核心编程 , --------

    2024年01月22日
    浏览(26)
  • C++提高编程——STL:string容器、vector容器

    本专栏记录C++学习过程包括C++基础以及数据结构和算法,其中第一部分计划时间一个月,主要跟着黑马视频教程,学习路线如下, 不定时更新,欢迎关注 。 当前章节处于: ---------第1阶段-C++基础入门 ---------第2阶段实战-通讯录管理系统, ---------第3阶段-C++核心编程, -----

    2024年01月23日
    浏览(35)
  • 【C++初阶】八、初识模板(泛型编程、函数模板、类模板)

    ========================================================================= 相关代码gitee自取 : C语言学习日记: 加油努力 (gitee.com)  ========================================================================= 接上期 : 【C++初阶】七、内存管理 (C/C++内存分布、C++内存管理方式、operator new / delete 函数、定位new表

    2024年02月04日
    浏览(32)
  • c++模板编程2-函数模板的定义和使用

    两阶段编译检查 在实例化模板的时候,如果模板的参数类型不支持模板中用到的操作符,将会遇到编译期错误,例: 以上例子 add(a, b) 会在编译器报错,但在模板定义的地方并没有出现错误提示,这是因为模板是分两步编译的: 在模板定义阶段,模板的检查并不包含类型参

    2024年02月06日
    浏览(22)
  • C++之模板编程

    模板及泛型编程与面向对象有根本的区别:显式接口和运行期多态仍存在,但重要性降低,隐式接口和编译期多态移到前头了;C++中的元编程指针对类型以及常数进行推导,演算和构造等操作,这些操作的共同特点是都是面向编译期逻辑,大多通过模板技巧实现 经验总结 只

    2024年02月03日
    浏览(22)
  • 【C++】C++泛型编程 | 模板初阶

      🧑‍🎓 个人主页:简 料   🏆 所属专栏:C++   🏆 个人社区:越努力越幸运社区   🏆 简       介: 简料简料,简单有料~在校大学生一枚,专注C/C++/GO的干货分享,立志成为您的好帮手 ~ C/C++学习路线 (点击解锁) ❤️ C语言 ❤️ 初阶数据结构与算法 ❤️ C++ ❤️

    2024年02月08日
    浏览(65)
  • 【C++】泛型编程——模板进阶

    在之前的文章里,我们进行了模板初阶的学习( 【C++】泛型编程——模板初阶),了解了什么是泛型编程,学习了函数模板和类模板。 那这篇文章,我们继续学习模板进阶的内容的学习。 首先我们来回顾一下: 我们在模板初阶的学习中,定义模板参数是怎么定义的? 是不

    2024年02月16日
    浏览(27)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包