代码包含一个自定义类型的栈,先进先出,使用[]提取栈中内容,使用std::cout进行输出内容。
#include <iostream>
using namespace std;
template <class T>
class Stack{
private:
T* stack;
int len;
public:
Stack():len(0){
stack = new T[100];
};
Stack(Stack &a){
this->stack = new T[100];
this->len = a.len;
for(int i=0; i<a.Get_len();i++){
this->stack[i] = a[i];
}
}
~Stack(){
delete[] stack;
};
void pop(const T a){
stack[len]=a;
len++;
}
void push(){
len--;
}
T operator[](const int a){
if(a<len) return stack[a];
else {
cout << "index out of bounds:" << a << endl;
return 0;
}
}
int Get_len(){
return len;
}
};
template <class T>
ostream & operator<<(ostream &out, Stack<T> st){
int i = 0;
for(;i<st.Get_len();i++){
out << st[i] << ' ';
}
return out;
}
int main(){
Stack<int> st;
st.pop(1);
st.pop(2);
st.pop(3);
st.push();
cout << st << endl;
Stack<string> st1;
st1.pop("aaa");
st1.pop("bbb");
st1.pop("ccc");
st1.push();
cout << st1 << endl;
}
以下为输出结果