0%

C++中指针栈模板的建立

方法

使用指针栈的方法之一是让调用程序提供一个指针数组,其中每个指针都是指向不同的字符串。把这些指针放在栈中是有意义的,因为每个指针都将指向不同的字符串。

注意

1、创建不同的指针式调用程序的指责,而不是栈的职责。栈的任务是管理指针,而不是创建指针。
2、对于指针栈来说,这里的Type类型一定是一种指针类型,如const char*之类。

1
template<class Type>

3、栈的成员变量items实际是一个二级指针,它用来记录存放栈元素的内存空间的地址,就像是一个数组中的数组名一样,只不过一般的数组中存放的是数据,这个数组中存放的是指针而已。

1
Type* items;//holds stack items

4、由于items类似于数组名,所以在析构函数中,处理方式就跟数组一样。

1
2
3
4
items = new Type[stacksize];
~Stack() { delete[]items; }//在这个实现中
str = new char[len+1];
~String(){delete[]str;}//在以前处理数组的方式

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#ifndef STCKTP1_H_
#define STCKTP1_H_
template<class Type>
class Stack
{
private:
enum{SIZE = 10};//default size
int stacksize;
Type* items;//holds stack items
int top;//index for top stack item
public:
explicit Stack(int ss = SIZE);
Stack(const Stack& st);
~Stack() { delete[]items; }
bool isempty() { return top == 0; }
bool isfull() { return top == stacksize; }
bool push(const Type& item);//add item to stack
bool pop(Type& item);//pop top into item
Stack& operator=(const Stack& st);
};
template<class Type>
Stack<Type>::Stack(int ss)::stacksize(ss), top(0)
{
items = new Type[stacksize];
}
template <class Type>
Stack<Type>::Stack(const Stack& st)
{
stacksize = st.stacksize;
top = st.top;
items = new Type[stacksize];
for (int i = 0; i < top; i++)
{
items[i] = st.items[i];
}
}
template<class Type>
bool Stack<Type>::push(const Type& item)
{
if (top < stacksize)
{
items[top++] = item;
return true;
}
else
{
return false;
}
}
template<class Type>
bool Stack<Type>::pop(Type& item)
{
if (top > 0)
{
item = items[--top];
return true;
}
else
{
return false;
}
}
template<class Type>
Stack<Type>& Stack<Type>::operator=(const Stack<Type>& st)
{
if (this == &st)
return *this;
delete[]items;
stacksize = st.stacksize;
top = st.top;
items = new Type[stacksize];
for (int i = 0; i < top; i++)
{
items[i] = st.items[i];
}
return *this;
}
#endif // !STCKTP1_H_