C++带异常处理的CharStack

头文件: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;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值