模板类的实例—栈

cpp 复制代码
#include<iostream>

using namespace std;

typedef int Datatype;

class Stack
{
private:
	Datatype* items;//栈数组
	int stacksize;//栈的实际大小
	int top;//栈顶指针
public:
	//构造函数:1)分配栈数组内存,2)把栈顶指针初始化为0;
	Stack(int size) :stacksize(size), top(0) {
		items = new Datatype [stacksize];
	}
	~Stack() {
		delete [] items;
		items = nullptr;
	}
	bool isempty()const {
		if (top == 0)return true;
		return false;
	}
	bool isfull()const {
		if (top == stacksize)return true;
		return false;
	}
	bool push(const Datatype& item) {
		//元素入栈;
		if (top < stacksize) {
			items[top++] = item; 
			return true;
		}
		return false;
	}
	bool pop(Datatype &item){
		if (top > 0) { item = items[--top]; return true; }
		return false;
	}
};
int main()
{
	Stack ss(5);

	//元素入栈;
	ss.push(1); ss.push(2); ss.push(3); ss.push(4); ss.push(5);
	//元素chu栈;
	Datatype item;
	while (ss.isempty() == false) {
		ss.pop(item);
		cout << "item = " << item << endl;
	}
	return 0;
}

接下来我们把这个普通类改为模板类;

cpp 复制代码
#include<iostream>

using namespace std;

template <class Datatype>
class Stack
{
private:
	Datatype* items;//栈数组
	int stacksize;//栈的实际大小
	int top;//栈顶指针
public:
	//构造函数:1)分配栈数组内存,2)把栈顶指针初始化为0;
	Stack(int size) :stacksize(size), top(0) {
		items = new Datatype [stacksize];
	}
	~Stack() {
		delete [] items;
		items = nullptr;
	}
	bool isempty()const {
		if (top == 0)return true;
		return false;
	}
	bool isfull()const {
		if (top == stacksize)return true;
		return false;
	}
	bool push(const Datatype& item) {
		//元素入栈;
		if (top < stacksize) {
			items[top++] = item; 
			return true;
		}
		return false;
	}
	bool pop(Datatype &item){
		if (top > 0) { item = items[--top]; return true; }
		return false;
	}
};
int main()
{
	Stack<int>ss(5);

	//元素入栈;
	ss.push(1); ss.push(2); ss.push(3); ss.push(4); ss.push(5);
	//元素chu栈;
	int item;
	while (ss.isempty() == false) {
		ss.pop(item);
		cout << "item = " << item << endl;
	}
	return 0;
}

创建模板类的方法:

先写一个普通类,用具体的数据类型。

调试普通类。

把普通类改为模板类;

相关推荐
ohyeah15 分钟前
栈:那个“先进后出”的小可爱,其实超好用!
前端·数据结构
自由生长202436 分钟前
为什么C++项目偏爱.cxx扩展名:从MongoDB驱动说起
c++
CSDN_RTKLIB44 分钟前
【GNU、GCC、g++、MinGW、MSVC】上
c++·gnu
b***74881 小时前
C++在系统中的内存对齐
开发语言·c++
散峰而望1 小时前
C++数组(三)(算法竞赛)
开发语言·c++·算法·github
q***95221 小时前
SpringMVC 请求参数接收
前端·javascript·算法
4***14901 小时前
C++在系统中的编译优化
开发语言·c++
mit6.8241 小时前
[HomeKey] 握手协议 | NFC协议处理器
c++
oioihoii1 小时前
C++程序执行起点不是main:颠覆你认知的真相
开发语言·c++
初级炼丹师(爱说实话版)1 小时前
多进程与多线程的优缺点及适用场景总结
算法