21.C++异常机制的处理原理try,throw,catch和堆栈的实现

#include <iostream>
using namespace std;
 
float Div(int a,int b)//throw(int,float)//表示只允许返回这两种类型异常
{
    if(b == 0)
    {
        short x;
        throw x;
    }
    return a*1.0/b;
}
 
int main()
{
    int a;
    int b;
    cin>>a>>b;
    float result =0.0f;
    try//测试语句
    {
        result = Div(a,b);
    }
    catch(int)//捕获语句返回的异常
    {
        cerr << "int b==0" << '\n';
    }
    catch(float)
    {
        cerr << "float b==0" << '\n';
    }
    catch(...)//其他异常返回
    {
        cerr << "b==0" << '\n';
    }
    cout<< result;
 
    return 0;
}

堆栈的实现

#include <iostream>
using namespace std;

template <typename Type>
class Stack
{
private:
    int capacity;
    int top;
    Type *idata;
    enum
    {
        STACK_SIZE = 8 //设置堆栈的最小数据结构
    };

public:
    Stack(int size = STACK_SIZE);
    ~Stack();

public:
    bool Push(const Type &data);
    bool Pop(void);
    bool IsFull();
    bool IsEmpty();
    void Show() const;
};

template <typename Type>
void Stack<Type>::Show() const//遍历栈元素,const方法是防止修改栈内元素
{
    for (int i = top - 1; i >= 0; i--)
        cout << idata[i] << endl;
}

template <typename Type>
bool Stack<Type>::IsFull()//是否满栈
{
    return top >= capacity;
}

template <typename Type>
bool Stack<Type>::IsEmpty()//是否是空栈
{
    return top <= 0;
}

template <typename Type>
bool Stack<Type>::Pop(void)//弹出
{
    if (IsEmpty())
    {
        cout << "Stack is empty !" << endl;
        return false;
    }
    else
    {
        top = top -1;
        return true;
    }
}

template <typename Type>
bool Stack<Type>::Push(const Type &data)//压栈
{
    if (IsFull())
    {
        cout << "Stack full !" << endl;
        return false;
    }
    else
    {
        idata[top++] = data;
        return true;
    }
}

template <typename Type>
Stack<Type>::Stack(int size)//初始化
{
    capacity = size > STACK_SIZE ? size : STACK_SIZE;
    idata = new Type[capacity];
    top = 0;
}

template <typename Type>
Stack<Type>::~Stack(/* args */)//析构
{
    if (idata != NULL)
        delete[] idata;
    idata = NULL;
    top = 0;
    capacity = 0;
}

int main()
{
    Stack<int> s(7);
    for (int i = 0; i < 10; i++)
    {
        s.Push(i);
    }
    s.Show();

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值