头文件:CharStack.h
#pragma once
#include<string>
#include<exception>
class CharStack
{
private:
char *elementData;
int capacity;
int top;
public:
CharStack(int capacity);
~CharStack(void);
int Size();
bool IsEmpty();
void Push(char c);
char Pop();
char Peek();
void Clear();
class CharStack_error : public std::runtime_error {
public:
CharStack_error(const std::string &str) : std::runtime_error(str){}
};
};
cpp文件:CharStack.cpp
#include "CharStack.h"
CharStack::CharStack(int capacity)
{
if(capacity<1) throw CharStack_error("capacity is less than 1");
this->capacity = capacity;
this->elementData = new char[capacity];
this->top = -1;
}
CharStack::~CharStack(void)
{
}
int CharStack::Size() {
return top + 1;
}
bool CharStack::IsEmpty() {
return top == -1;
}
void CharStack::Push(char c) {
if(top==capacity-1) throw CharStack_error("Stack is Full");
elementData[++top] = c;
}
char CharStack::Pop() {
if(IsEmpty()) throw CharStack_error("Stack is Empty");
return elementData[top--];
}
char CharStack::Peek() {
if(IsEmpty()) throw CharStack_error("Stack is Empty");
return elementData[top];
}
void CharStack::Clear() {
top = -1;
}
测试代码:
#include"CharStack.h"
#include<iostream>
int main() {
try{
CharStack stack(2);
//stack.Push('a');
//stack.Push('b');
//stack.Push('c');
std::cout << stack.Pop();
}catch(const CharStack::CharStack_error &e) {
std::cerr << e.what() << std::endl;
}
}