用面向对象的方法实现一个整型栈
#include<iostream>
using namespace std;
class MyStack
{
private:
enum{STACK_INIT_SIZE=10,STACK_INC_SIZE=2}; //枚举
int* _data; //指向一片连续空间
int _size; //栈的大小
int _top; //栈顶
bool Resize(size_t new_sz)
{
if(new_sz<=Size())
{
new_sz=Size()*2;
}
int* newdata=new(nothrow) int[new_sz]; //申请新的空间大小
if(nullptr==newdata)
{
rerurn false;
}
int sz=Size();
memove(newdata,_data,_sz*sizeof(int)); //将原来的拷贝到新
//空间中去,同时给出字节数拷贝
delete[] _data; //释放原有的空间
_data=newdata; //将新地址赋值给_data
_size=new_sz; //将新容量赋值给_size
return true;
}
public:
MyStack():_data(nullptr),_size(STACK_INIT_SIZE),_top(-1) //构造函数
{
_data=new int[_size];
}
MyStack(int sz):_data(nullptr),_size(sz),_top(-1)
{
_data=new int[_size];
}
~MyStack() //析构函数释放资源
{
delete[] _data;
_data=nullptr;
_size=0;
_top=-1;
}
size_t Size() const //在成员函数只是对对象属性进行读取操作时,最好为常
//函数
{
return top+1;
}
bool Empty() const{return Size()==0;}//判断是否为空栈
bool Full() const{return Size()==_size;} //判断是否满
void Push(int val) //入栈
{
if(Full()&&) return false;
_data[++_top]=val; //先抬栈再赋值元素
return true;
}
int &Top(){return _data[_top];} //返回栈顶元素
const int& Top() const{return _data[_top];}
bool Pop() //出栈
{
if(Empty()) return false;
_top=_top-1;
return true;
}
bool GetPop(int &val) //出栈并且输出元素值
{
if(Empty()) return false;
val=_data[_top];
_top-=1;
return true;
}
};
void fun(const MyStack& s)
{
}
int main()
{
MyStack mys;
for(int i=0;i<10;++i)
{
cout<<"Push: "<<i<<" "<<mys.Push(i)<<endl;
}
while(!mys.Empty())
{
int x=mys.Top();
mys.Pop();
cout<<x<<endl;
}
}