同样先满足了StackOfIntegers的基本功能。
在题目要求的peek和pop判断为空时throw自定义的类EmptyStackException并写好对应的what即可。
#include <iostream>
#include <string>
using namespace std;
class EmptyStackException
{
public:
EmptyStackException()
{
}
string what()
{
return "Empty Stack Exception";
}
}error;
class StackOfIntegers
{
public:
StackOfIntegers()
{
size = 0;
array = new int[100];
}
bool empty()
{
return size == 0;
}
int peek()
{
if (size == 0)
{
throw error;
}
else return array[size - 1];
}
void push(int value)
{
array[size++] = value;
}
int pop()
{
if (size == 0)
{
throw error;
}
else return array[--size];
}
int getSize()
{
return size;
}
private:
int size;
int *array;
};
//以上是要提交的部分
/*Define a custom exception class named EmptyStackException and let the peek and pop
function throw an ExmptyStackException if the stack is empty.*/
void f()
{
StackOfIntegers s;
try
{
s.peek();
}
catch (EmptyStackException ex)
{
cout << ex.what() << endl;
}
try
{
s.pop();
}
catch (EmptyStackException ex)
{
cout << ex.what() << endl;
}
}
int main()
{
f();
return 0;
}