21.C++异常机制的处理原理try,throw,catch

21.C++异常机制的处理原理try,throw,catch,第1张

21.C++异常机制的处理原理try,throw,catch
#include 
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 
using namespace std;

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

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

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

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

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

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

template 
Stack::~Stack()//析构
{
    if (idata != NULL)
        delete[] idata;
    idata = NULL;
    top = 0;
    capacity = 0;
}

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

    return 0;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5610872.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存