构造函数用于获取资源!
构造函数返回值返回的是地址
析构函数返回值
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
using namespace std;
template<class Type>
class SeqStack//栈 先进后出
{
private://私有数据成员
Type* data;//数据
int maxsize;//最大长度
int top;//栈顶
public://公有成员
SeqStack(int sz = 10) :maxsize(sz), top(-1)//最大栈长为10 top为-1
{
data = (Type*)malloc(sizeof(Type) * maxsize);//malloc 动态内存分配但没有指定名字
if (data == NULL)exit(1);
}
~SeqStack()//析构函数
{
free(data);//释放
data = NULL;
maxsize = 0;
top = -1;
}
int GetSize() const { return top + 1; }//逐次加一
bool Is_Empty() const { return GetSize()==0; }
bool Is_Full() const { return GetSize() == maxsize; }//若满则为最大长度
bool Push(const Type& x)
{
if (Is_Full()) return false;
data[++top] = x;
return true;
}
Type& GetTop()
{
return data[top];
}
const Type& GetTop() const
{
return data[top];
}
void Pop()
{
--top;
}
};
int main()
{
SeqStack<int> ist = SeqStack<int>();
ist.Push(12);
ist.Push(23);
ist.Push(34);
ist.Push(45);
while (!ist.Is_Empty())
{
int x = ist.GetTop();
ist.Pop();
cout << x << endl;
}
return 0;
}
栈:先进后出