84 lines
2.0 KiB
C++
84 lines
2.0 KiB
C++
// 异常与模版
|
||
// 异常处理循环问题的示例
|
||
#include <iostream>
|
||
#include <exception>
|
||
|
||
using namespace std;
|
||
|
||
template <typename T>
|
||
class Stack
|
||
{
|
||
private:
|
||
T *mData; // 数据
|
||
int mCapacity; // 容量
|
||
int mIndex; // 索引
|
||
|
||
public:
|
||
// -1 表示栈为空
|
||
Stack(int capacity) : mCapacity(capacity), mIndex(-1)
|
||
{
|
||
this->mData = new T[this->mCapacity];
|
||
}
|
||
~Stack()
|
||
{
|
||
delete[] this->mData; // 释放内存
|
||
mData = nullptr; // 防止野指针
|
||
}
|
||
|
||
public:
|
||
T pop() throw(out_of_range)
|
||
{
|
||
if (mIndex < 0)
|
||
throw out_of_range("当前栈未空,请先压栈");
|
||
return this->mData[this->mIndex--];
|
||
}
|
||
Stack<T> &push(const T &item) throw(out_of_range)
|
||
{
|
||
if (mIndex >= mCapacity - 1) // >= 表示栈满 , mCapacity - 1 表示栈顶
|
||
throw out_of_range("当前栈已满,请先出栈");
|
||
this->mData[++this->mIndex] = item;
|
||
return *this; // 返回当前对象,支持链式编程
|
||
}
|
||
T &at(int index) throw(out_of_range)
|
||
{
|
||
// mIndex == -1 表示栈为空,index < 0 表示索引小于 0,index > mIndex 表示索引大于栈顶
|
||
if (mIndex == -1 || index < 0 || index > mIndex)
|
||
throw out_of_range("当前栈为空或位置无效");
|
||
return this->mData[index];
|
||
}
|
||
int size() const
|
||
{
|
||
return this->mIndex + 1;
|
||
}
|
||
};
|
||
|
||
int main()
|
||
{
|
||
Stack<int> s1(5);
|
||
s1.push(10).push(20).push(30);
|
||
for (int i = 0; i < s1.size(); i++)
|
||
cout << s1.at(i) << endl;
|
||
|
||
cout << "*** 弹出数据 ***" << endl;
|
||
// 清空数据
|
||
while (1)
|
||
|
||
{
|
||
try
|
||
{
|
||
cout << s1.pop() << endl;
|
||
}
|
||
catch (exception &e)
|
||
{
|
||
cout << "error: " << e.what() << endl;
|
||
break; // 异常处理: 跳出循环
|
||
}
|
||
}
|
||
|
||
cout << "*** 弹栈完成,重新打印 ***" << endl;
|
||
for (int i = 0; i < s1.size(); i++)
|
||
cout << s1.at(i) << endl;
|
||
|
||
return 0;
|
||
}
|