#include <iostream>
using namespace std;
//const int CAP = 5;
//typedef int T;
//Array<T>
template <class T>
class Stack
{
private:
int n;//已放元素个数
// T arr[CAP];
T* arr;
int cap; //将固定大小的arr 改成 可调大小的arr cap为容量
public:
Stack(int cap=3):n(0),arr(new T[cap]),cap(cap){/*cout<<"Stack()"<<endl;*/}
~Stack(){delete[] arr; /*cout<<"~Stack()"<<endl;*/}
Stack(const Stack& s); //拷贝构造函数 是为arr 和 cap服务 因为是在类里面需要把东西给构造出来
Stack& operator=(const Stack& s); //下面涉及到对cap的赋值 需要用到“=” 则用到运算符重载
//拷贝构造函数,运算符重载,模板类三件套
void push(const T& t)
{
if(full())throw "stack overflow";
arr[n++]=t;
}
void pop()
{
if(empty())throw "stack empty";
--n;
}
T top()
{
if(empty())throw "stack empty";
return arr[n-1];
}
bool empty(){return n==0;}
bool full(){return n==cap;}
int& size(){return n;} //*
void clear(){n=0;}
int capacoty(){return cap;}
};
template <typename T>
Stack<T>::Stack(const Stack& s)
{
cout<<"Stack(copy)"<<endl;
n=s.n;
arr = new T[s.cap];
cap = s.cap;
for(int i=0;i<n;++i)
{
arr[i] = s.arr[i];
}
}
template <typename T>
Stack<T>& Stack<T>:: operator=(const Stack& s)
{
if(this==&s)return *this;
delete[] arr;
n=s.n;
arr = new T[s.cap];
cap = s.cap;
for(int i=0;i<n;++i)
{
arr[i] = s.arr[i];
}
return *this;
}
template <typename T>
void show(Stack<T> &s) //T s
{
int n = s.size();
while(!s.empty())
{
cout<<s.top()<<" ";
s.pop();
}
cout<<endl;
s.size() = n;
}
int main004()
{
try {
int* p = new int; //new int 本就是声明一个空间是地址 因此p也必须是指针
// *p = 4;
cout<<"*p="<<*p<<endl;
// int* pi = new int;
// double* pd = new double;
// string* ps = new string; //string(); string s;
// string* ps2 = new string(3); //string(int) NO 建内存的本质是调用构造函数
// string* ps22 = new string(3,'\0');
// string* ps222 = new string("3"/*"wepull"*/);
// string* ps3 = new string[3];
Stack<char> sc(4);
sc.push('A');sc.push('B');sc.push('C');sc.push('S');
show(sc);
Stack<char> sc2(sc);
show(sc2);
Stack<char> sc3;
sc3 = sc;
show(sc3);
Stack<int> si;
si.push(1);si.push(2);si.push(3);
show(si);
Stack<string> ss;
ss.push("AAA");ss.push("ABC");ss.push("VVV");
show(ss);
} catch (const char* e) {
cout<<"e:"<<e<<endl;
}
return 0;
}