重载输入运算符

本文介绍了一个使用C++实现的模板栈类(seqStack),该类基于数组实现,并支持基本的栈操作如push、pop等。文章提供了完整的源代码,包括如何处理栈溢出的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <assert.h>
#include <iostream>
#include "myStack.h"

using namespace std;


const int stackIncreament = 20;
template <class T>
class seqStack :public myStack<T>   //不能写作public myStack因为继承的是模板类,所以public myStack<T>
{
public:
	seqStack (int sz=50) ;//构造函数为空
	
	 void push(T & x);
	 bool pop(T & x);//栈顶元素出栈,由x返回
	 bool getPop(T & x)const;//读取栈顶元素由x返回
	 bool isEmpty() const
	 {
		 return (top ==  - 1) ? true : false;
	 }
	 bool isFull() 
	 {
		 return (top == maxSize - 1) ? true : false;
	 }
	 friend std::ostream & operator <<(std::ostream & os, seqStack<T> & s)//只能定义在内部
	{
		os << "top=" << s.top << endl;
		for (int i = 0; i < s.top; i++)
		{
			os << i << ":" << s.element[i] << endl;
		}
		return os;
	}
private:
	T * element;
	int top;//top不是指针
	int maxSize;//没有私有数据成员
	void overFlow();
};
template <class T>
seqStack<T>::seqStack(int sz = 50)
{
	maxSize = sz;
	top = -1;
	element=new T[maxSize];
	assert(element != NULL);
}


template <class T>
void seqStack<T>::overFlow()
{
	T * newArray = new T[maxSize + stackIncreament]; 
	if (newArray==NULL)
	{
		cerr << "储存分配失败!" << endl; exit(1);
	}
	for (int  i = 0; i < top; i++)
	{
		newArray[i] = element[i];
		maxSize = maxSize + stackIncreament;
		delete[]element;
	}
}

template <class T>
void seqStack<T>::push(T & x)
{
	if (isFull() == true)
	{
		overFlow();
	}

	
		element[++top] = x;
	
}
template <class T>
bool seqStack<T>::pop(T & x)
{
	if (isEmpty() == true)
	{
		return false;
	}
	else
	{
		  x= element[top];
		  --top;
		  return true;
	}
}
template <class T>
bool seqStack<T>::getPop(T & x) const
{
	if (isEmpty() == true)
	{
		return false;
	}
	else
	{
		x = element[top];
		
		return x;
	}
}
 
template <class T>
 std::ostream & operator <<(std::ostream & os, seqStack<T> & s)//只能定义在内部,这样错误
	{
		os << "top=" << s.top << endl;
		for (int i = 0; i < s.top; i++)
		{
			os << i << ":" << s.element[i] << endl;
		}
		return os;
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值