1.模板类实现顺序栈
#include <iostream>
#define MAX 8
using namespace std;
template<typename T>
class stack
{T data[MAX];int top;
public:stack():top(-1){}bool empty_stack();bool full_stack();void push_stack(T data);void pop_stack();void show();
};template<typename T>
bool stack<T>::empty_stack()
{return top == -1;
}template<typename T>
bool stack<T>::full_stack()
{return top == MAX-1;
}template<typename T>
void stack<T>::push_stack(T data)
{if(full_stack()){return;}top++;this->data[top] = data;return;
}template<typename T>
void stack<T>::pop_stack()
{if(empty_stack()){cout<<"栈为空"<<endl;return;}cout<<"出栈的元素为"<<data[top]<<endl;top--;return;
}template<typename T>
void stack<T>::show()
{if(empty_stack()){cout<<"栈为空"<<endl;return;}for(int i=0;i<=top;i++){cout<<data[i];}cout<<endl;
}int main()
{stack<int>s1;s1.push_stack(1);s1.push_stack(2);s1.push_stack(3);s1.push_stack(4);s1.push_stack(5);s1.push_stack(6);s1.push_stack(7);s1.push_stack(8);s1.show();s1.pop_stack();s1.show();cout<<s1.full_stack()<<endl;return 0;
}
2. char类型的字符数组,实现对数组越界的抛出异常并处理
#include <iostream>
#include <cstring>
using namespace std;
void arr_size(const char *p,int size)
{int len = strlen(p);//5if(size>=len){throw int(0);}
}
int main()
{char arr[6] = "hello";int size = 4;int size2 = 8;try{arr_size(arr,size);} catch (int ret){if(ret==0){cout<<"数组越界"<<endl;}}try{arr_size(arr,size2);} catch (int ret){if(ret==0){cout<<"数组越界"<<endl;}}cout<<arr[size]<<endl;cout<<arr[size2]<<endl;return 0;
}