代码拉取完成,页面将自动刷新
#pragma once
#include <iostream>
#include "stack.h"
using namespace std;
//// 顺序栈模板类
//template <class TData> class SeqStack;
//
//// 重载<<
//template <typename TData> ostream& operator<<(ostream& os, const SeqStack<TData>& seq_stack);
template <class TData>
class SeqStack :public Stack<TData>
{
// 友元函数没有权限控制符:它不属于类的成员,因此无法受到 public、protected 或 private 的限制。
// 重载<<
/* <> 这对尖括号表明这是一个函数模板的友元声明,是模板参数推断。
* 因为 SeqStack 是一个类模板,友元函数也需要是模板函数,
* 而 <> 表明我们要匹配一个任意类型 TData 的模板函数。
*/
/*
* 当某个非成员函数或其他类的成员函数需要访问类的私有成员时。
*如果函数的功能比较独立,不适合作为类的成员函数,但需要访问类的私有数据时,可以将其声明为友元函数。
*/
friend ostream& operator<< <>(ostream& os, const SeqStack<TData>& seq_stack);
private:
TData* mem_data_;
int capacity_;
int top_; // 指向入栈的栈顶元素
public:
explicit SeqStack(int capacity = 20) :capacity_(capacity_), top_(-1)
{
// mem_data_ 指向的是这个动态数组的第一个元素,而不是数组本身。
// C++中没有数组类型的指针,数组名(或指针)指向的是数组的首个元素
this->mem_data_ = new TData[this->capacity_];
if (!this->mem_data_)
throw bad_alloc();
}
~SeqStack();
virtual bool push(const TData& data) override;
virtual bool pop(TData& data) override;
bool pop();
virtual bool top(TData& data) const override;
virtual bool isEmpty() const override;
virtual int length() const override;
bool isFull() const;
void clear();
};
// 重载<<是为了cout << object; 可以直接输出object的相关信息
template <typename TData>
ostream& operator<<(ostream& os, const SeqStack<TData>& seq_stack)
{
os << "栈中元素的个数:" << seq_stack.length() << endl;
// 从栈顶开始输出
for (int i = seq_stack.top_; i >= 0; i--)
{
os << seq_stack.mem_data_[i] << endl;
}
return os; // 为了支持链式编程 如cout << object; cout << endl; ===> cout << object << endl;
}
template<class TData>
inline SeqStack<TData>::~SeqStack()
{
delete[] this->mem_data_;
}
template<class TData>
inline bool SeqStack<TData>::push(const TData& data)
{
if (this->isFull())
return false;
this->top_++;
this->mem_data_[this->top_] = data;
return true;
}
template<class TData>
inline bool SeqStack<TData>::pop(TData& data)
{
if (this->length() == 0)
return false;
data = this->mem_data_[this->top_];
this->top_--;
return true;
}
template<class TData>
inline bool SeqStack<TData>::pop()
{
if (this->length() == 0)
return false;
this->top_--;
return true;
}
template<class TData>
inline bool SeqStack<TData>::top(TData& data) const
{
if (this->length() == 0)
return false;
data = this->mem_data_[this->top_];
return true;
}
template<class TData>
inline bool SeqStack<TData>::isEmpty() const
{
return this->top_ == -1;
}
template<class TData>
inline int SeqStack<TData>::length() const
{
return this->top_ + 1;
}
template<class TData>
inline bool SeqStack<TData>::isFull() const
{
return this->top_ == this->capacity_ - 1;
}
// 删除栈中的实体元素
template<class TData>
inline void SeqStack<TData>::clear()
{
int length = this->length();
if (length == 0)
return;
for (int i = 0; i < length; i++)
this->pop();
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。