头文件: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;
}
}
本文介绍了一个简单的字符栈类的设计与实现过程,包括主要成员变量和成员函数的定义。此外,还提供了一个简单的测试示例来验证字符栈的功能。文章详细展示了如何处理栈满和栈空的情况,并通过自定义异常来增强程序的健壮性。
554

被折叠的 条评论
为什么被折叠?



