有人可以指出用异常处理来执行这个程序的正确方法吗?这是一个堆栈程序。
1)#include<iostream>
2)#include<stdlib.h>
3)#include<string.h>
4)using namespace std;
5)
6)template<class T>
7)class Stack {
8)private:
9) int max;
10) int top;
12) T* items;
13)public:
14) Stack(int size) {
15) max = size;
16) top = -1;
17) items = new T[max];
18) }
19) ~Stack(){delete [] items;}
20)
21) void push(T data) throws Exception{
22) if(full()) {
23) throw new StackException("Out of space!");
24) }
25) items[++top] = data;
26) }
27) T pop(){
28) if(empty()) throws Exception {
29) throw new StackException("No more elements to delete");
30) }
31) return items[top--];
32) }
33)
34) bool full() { return top == max-1; }
35) bool empty() { return top == -1; }
36)};
37)
38)int main() {
39) try{
40) Stack<int> s(10);
41) s.push(1);
42) s.push(2);
43) cout<<s.pop()<<endl;
44) }
45) catch(StackException e){
46) cout<<e.what()<<endl;
47) }
48) return 0;
49)}
编辑:我收到以下错误。我是 C++ 异常处理的新手,想知道我是否做得对——
3stacks.cpp:20:18: error: expected ‘;’ at end of member declaration
3stacks.cpp:20:20: error: ‘throws’ does not name a type
3stacks.cpp:26:8: error: expected ‘;’ at end of member declaration
3stacks.cpp:26:10: error: ‘throws’ does not name a type
3stacks.cpp: In function ‘int main()’:
3stacks.cpp:44:8: error: expected type-specifier before ‘StackException’
3stacks.cpp:44:23: error: expected ‘)’ before ‘e’
3stacks.cpp:44:23: error: expected ‘{’ before ‘e’
3stacks.cpp:44:23: error: ‘e’ was not declared in this scope
3stacks.cpp:44:24: error: expected ‘;’ before ‘)’ token